blob: 780a26e6b1be8bc9de4df2324d4168116ff2841b [file] [log] [blame]
David Tolnay864ab8c2020-03-29 22:25:40 -07001//! **[https://github.com/dtolnay/cxx]**
2//!
3//! <br>
4//!
David Tolnay7db73692019-10-20 14:51:12 -04005//! This library provides a **safe** mechanism for calling C++ code from Rust
6//! and Rust code from C++, not subject to the many ways that things can go
7//! wrong when using bindgen or cbindgen to generate unsafe C-style bindings.
8//!
David Tolnayccd39752020-01-08 09:33:51 -08009//! This doesn't change the fact that 100% of C++ code is unsafe. When auditing
10//! a project, you would be on the hook for auditing all the unsafe Rust code
11//! and *all* the C++ code. The core safety claim under this new model is that
12//! auditing just the C++ side would be sufficient to catch all problems, i.e.
13//! the Rust side can be 100% safe.
14//!
David Tolnay7db73692019-10-20 14:51:12 -040015//! <br>
16//!
David Tolnayb606ce32020-03-16 01:16:16 -070017//! *Compiler support: requires rustc 1.42+*
David Tolnay7db73692019-10-20 14:51:12 -040018//!
19//! <br>
20//!
21//! # Overview
22//!
23//! The idea is that we define the signatures of both sides of our FFI boundary
24//! embedded together in one Rust module (the next section shows an example).
25//! From this, CXX receives a complete picture of the boundary to perform static
26//! analyses against the types and function signatures to uphold both Rust's and
27//! C++'s invariants and requirements.
28//!
29//! If everything checks out statically, then CXX uses a pair of code generators
30//! to emit the relevant `extern "C"` signatures on both sides together with any
31//! necessary static assertions for later in the build process to verify
32//! correctness. On the Rust side this code generator is simply an attribute
33//! procedural macro. On the C++ side it can be a small Cargo build script if
34//! your build is managed by Cargo, or for other build systems like Bazel or
35//! Buck we provide a command line tool which generates the header and source
36//! file and should be easy to integrate.
37//!
38//! The resulting FFI bridge operates at zero or negligible overhead, i.e. no
39//! copying, no serialization, no memory allocation, no runtime checks needed.
40//!
41//! The FFI signatures are able to use native types from whichever side they
42//! please, such as Rust's `String` or C++'s `std::string`, Rust's `Box` or
43//! C++'s `std::unique_ptr`, Rust's `Vec` or C++'s `std::vector`, etc in any
44//! combination. CXX guarantees an ABI-compatible signature that both sides
45//! understand, based on builtin bindings for key standard library types to
46//! expose an idiomatic API on those types to the other language. For example
47//! when manipulating a C++ string from Rust, its `len()` method becomes a call
48//! of the `size()` member function defined by C++; when manipulation a Rust
49//! string from C++, its `size()` member function calls Rust's `len()`.
50//!
51//! <br>
52//!
53//! # Example
54//!
55//! A runnable version of this example is provided under the *demo-rs* directory
David Tolnayd763f182020-03-12 00:50:19 -070056//! of [https://github.com/dtolnay/cxx] (with the C++ side of the implementation
David Tolnay7db73692019-10-20 14:51:12 -040057//! in the *demo-cxx* directory). To try it out, jump into demo-rs and run
58//! `cargo run`.
59//!
60//! ```no_run
61//! #[cxx::bridge]
62//! mod ffi {
63//! // Any shared structs, whose fields will be visible to both languages.
64//! struct SharedThing {
65//! z: i32,
66//! y: Box<ThingR>,
67//! x: UniquePtr<ThingC>,
68//! }
69//!
70//! extern "C" {
71//! // One or more headers with the matching C++ declarations. Our code
72//! // generators don't read it but it gets #include'd and used in static
73//! // assertions to ensure our picture of the FFI boundary is accurate.
74//! include!("demo-cxx/demo.h");
75//!
76//! // Zero or more opaque types which both languages can pass around but
77//! // only C++ can see the fields.
78//! type ThingC;
79//!
80//! // Functions implemented in C++.
81//! fn make_demo(appname: &str) -> UniquePtr<ThingC>;
David Tolnay7db73692019-10-20 14:51:12 -040082//! fn do_thing(state: SharedThing);
Joel Galensonf9379962020-04-16 14:11:25 -070083//!
84//! // Methods implemented in C++.
85//! fn get_name(self: &ThingC) -> &CxxString;
David Tolnay7db73692019-10-20 14:51:12 -040086//! }
87//!
88//! extern "Rust" {
89//! // Zero or more opaque types which both languages can pass around but
90//! // only Rust can see the fields.
91//! type ThingR;
92//!
93//! // Functions implemented in Rust.
94//! fn print_r(r: &ThingR);
Joel Galensonf9379962020-04-16 14:11:25 -070095//!
96//! // Methods implemented in Rust.
97//! fn print(self: &ThingR);
David Tolnay7db73692019-10-20 14:51:12 -040098//! }
99//! }
100//! #
101//! # pub struct ThingR(usize);
102//! #
103//! # fn print_r(r: &ThingR) {
104//! # println!("called back with r={}", r.0);
105//! # }
106//! #
Joel Galensonf9379962020-04-16 14:11:25 -0700107//! # impl ThingR {
108//! # fn print(&self) {
109//! # println!("method called back with r={}", self.0);
110//! # }
111//! # }
112//! #
David Tolnay7db73692019-10-20 14:51:12 -0400113//! # fn main() {}
114//! ```
115//!
116//! Now we simply provide C++ definitions of all the things in the `extern "C"`
117//! block and Rust definitions of all the things in the `extern "Rust"` block,
118//! and get to call back and forth safely.
119//!
120//! Here are links to the complete set of source files involved in the demo:
121//!
122//! - [demo-rs/src/main.rs](https://github.com/dtolnay/cxx/blob/master/demo-rs/src/main.rs)
123//! - [demo-rs/build.rs](https://github.com/dtolnay/cxx/blob/master/demo-rs/build.rs)
124//! - [demo-cxx/demo.h](https://github.com/dtolnay/cxx/blob/master/demo-cxx/demo.h)
125//! - [demo-cxx/demo.cc](https://github.com/dtolnay/cxx/blob/master/demo-cxx/demo.cc)
126//!
127//! To look at the code generated in both languages for the example by the CXX
128//! code generators:
129//!
130//! ```console
131//! # run Rust code generator and print to stdout
132//! # (requires https://github.com/dtolnay/cargo-expand)
133//! $ cargo expand --manifest-path demo-rs/Cargo.toml
134//!
135//! # run C++ code generator and print to stdout
136//! $ cargo run --manifest-path cmd/Cargo.toml -- demo-rs/src/main.rs
137//! ```
138//!
139//! <br>
140//!
141//! # Details
142//!
143//! As seen in the example, the language of the FFI boundary involves 3 kinds of
144//! items:
145//!
146//! - **Shared structs** &mdash; their fields are made visible to both
147//! languages. The definition written within cxx::bridge is the single source
148//! of truth.
149//!
150//! - **Opaque types** &mdash; their fields are secret from the other language.
151//! These cannot be passed across the FFI by value but only behind an
152//! indirection, such as a reference `&`, a Rust `Box`, or a `UniquePtr`. Can
153//! be a type alias for an arbitrarily complicated generic language-specific
154//! type depending on your use case.
155//!
156//! - **Functions** &mdash; implemented in either language, callable from the
157//! other language.
158//!
159//! Within the `extern "C"` part of the CXX bridge we list the types and
160//! functions for which C++ is the source of truth, as well as the header(s)
161//! that declare those APIs. In the future it's possible that this section could
162//! be generated bindgen-style from the headers but for now we need the
163//! signatures written out; static assertions will verify that they are
164//! accurate.
165//!
166//! Within the `extern "Rust"` part, we list types and functions for which Rust
167//! is the source of truth. These all implicitly refer to the `super` module,
168//! the parent module of the CXX bridge. You can think of the two items listed
169//! in the example above as being like `use super::ThingR` and `use
170//! super::print_r` except re-exported to C++. The parent module will either
171//! contain the definitions directly for simple things, or contain the relevant
172//! `use` statements to bring them into scope from elsewhere.
173//!
174//! Your function implementations themselves, whether in C++ or Rust, *do not*
175//! need to be defined as `extern "C"` ABI or no\_mangle. CXX will put in the
176//! right shims where necessary to make it all work.
177//!
178//! <br>
179//!
180//! # Comparison vs bindgen and cbindgen
181//!
182//! Notice that with CXX there is repetition of all the function signatures:
183//! they are typed out once where the implementation is defined (in C++ or Rust)
184//! and again inside the cxx::bridge module, though compile-time assertions
185//! guarantee these are kept in sync. This is different from [bindgen] and
186//! [cbindgen] where function signatures are typed by a human once and the tool
187//! consumes them in one language and emits them in the other language.
188//!
189//! [bindgen]: https://github.com/rust-lang/rust-bindgen
190//! [cbindgen]: https://github.com/eqrion/cbindgen/
191//!
192//! This is because CXX fills a somewhat different role. It is a lower level
193//! tool than bindgen or cbindgen in a sense; you can think of it as being a
194//! replacement for the concept of `extern "C"` signatures as we know them,
195//! rather than a replacement for a bindgen. It would be reasonable to build a
196//! higher level bindgen-like tool on top of CXX which consumes a C++ header
197//! and/or Rust module (and/or IDL like Thrift) as source of truth and generates
198//! the cxx::bridge, eliminating the repetition while leveraging the static
199//! analysis safety guarantees of CXX.
200//!
201//! But note in other ways CXX is higher level than the bindgens, with rich
202//! support for common standard library types. Frequently with bindgen when we
203//! are dealing with an idiomatic C++ API we would end up manually wrapping that
204//! API in C-style raw pointer functions, applying bindgen to get unsafe raw
205//! pointer Rust functions, and replicating the API again to expose those
206//! idiomatically in Rust. That's a much worse form of repetition because it is
207//! unsafe all the way through.
208//!
209//! By using a CXX bridge as the shared understanding between the languages,
210//! rather than `extern "C"` C-style signatures as the shared understanding,
211//! common FFI use cases become expressible using 100% safe code.
212//!
213//! It would also be reasonable to mix and match, using CXX bridge for the 95%
214//! of your FFI that is straightforward and doing the remaining few oddball
215//! signatures the old fashioned way with bindgen and cbindgen, if for some
216//! reason CXX's static restrictions get in the way. Please file an issue if you
217//! end up taking this approach so that we know what ways it would be worthwhile
218//! to make the tool more expressive.
219//!
220//! <br>
221//!
222//! # Cargo-based setup
223//!
224//! For builds that are orchestrated by Cargo, you will use a build script that
225//! runs CXX's C++ code generator and compiles the resulting C++ code along with
226//! any other C++ code for your crate.
227//!
228//! The canonical build script is as follows. The indicated line returns a
229//! [`cc::Build`] instance (from the usual widely used `cc` crate) on which you
230//! can set up any additional source files and compiler flags as normal.
231//!
232//! [`cc::Build`]: https://docs.rs/cc/1.0/cc/struct.Build.html
233//!
234//! ```no_run
235//! // build.rs
236//!
237//! fn main() {
238//! cxx::Build::new()
239//! .bridge("src/main.rs") // returns a cc::Build
240//! .file("../demo-cxx/demo.cc")
241//! .flag("-std=c++11")
242//! .compile("cxxbridge-demo");
243//!
244//! println!("cargo:rerun-if-changed=src/main.rs");
245//! println!("cargo:rerun-if-changed=../demo-cxx/demo.h");
246//! println!("cargo:rerun-if-changed=../demo-cxx/demo.cc");
247//! }
248//! ```
249//!
250//! <br><br>
251//!
252//! # Non-Cargo setup
253//!
254//! For use in non-Cargo builds like Bazel or Buck, CXX provides an alternate
255//! way of invoking the C++ code generator as a standalone command line tool.
256//! The tool is packaged as the `cxxbridge-cmd` crate on crates.io or can be
David Tolnayd763f182020-03-12 00:50:19 -0700257//! built from the *cmd* directory of [https://github.com/dtolnay/cxx].
David Tolnay7db73692019-10-20 14:51:12 -0400258//!
259//! ```bash
260//! $ cargo install cxxbridge-cmd
261//!
262//! $ cxxbridge src/main.rs --header > path/to/mybridge.h
263//! $ cxxbridge src/main.rs > path/to/mybridge.cc
264//! ```
265//!
266//! <br>
267//!
268//! # Safety
269//!
270//! Be aware that the design of this library is intentionally restrictive and
271//! opinionated! It isn't a goal to be powerful enough to handle arbitrary
272//! signatures in either language. Instead this project is about carving out a
273//! reasonably expressive set of functionality about which we can make useful
274//! safety guarantees today and maybe extend over time. You may find that it
275//! takes some practice to use CXX bridge effectively as it won't work in all
276//! the ways that you are used to.
277//!
278//! Some of the considerations that go into ensuring safety are:
279//!
280//! - By design, our paired code generators work together to control both sides
281//! of the FFI boundary. Ordinarily in Rust writing your own `extern "C"`
282//! blocks is unsafe because the Rust compiler has no way to know whether the
283//! signatures you've written actually match the signatures implemented in the
284//! other language. With CXX we achieve that visibility and know what's on the
285//! other side.
286//!
287//! - Our static analysis detects and prevents passing types by value that
288//! shouldn't be passed by value from C++ to Rust, for example because they
289//! may contain internal pointers that would be screwed up by Rust's move
290//! behavior.
291//!
292//! - To many people's surprise, it is possible to have a struct in Rust and a
293//! struct in C++ with exactly the same layout / fields / alignment /
294//! everything, and still not the same ABI when passed by value. This is a
295//! longstanding bindgen bug that leads to segfaults in absolutely
296//! correct-looking code ([rust-lang/rust-bindgen#778]). CXX knows about this
297//! and can insert the necessary zero-cost workaround transparently where
298//! needed, so go ahead and pass your structs by value without worries. This
299//! is made possible by owning both sides of the boundary rather than just
300//! one.
301//!
302//! - Template instantiations: for example in order to expose a UniquePtr\<T\>
303//! type in Rust backed by a real C++ unique\_ptr, we have a way of using a
304//! Rust trait to connect the behavior back to the template instantiations
305//! performed by the other language.
306//!
307//! [rust-lang/rust-bindgen#778]: https://github.com/rust-lang/rust-bindgen/issues/778
308//!
309//! <br>
310//!
311//! # Builtin types
312//!
David Tolnay559fbb32020-03-17 23:32:20 -0700313//! In addition to all the primitive types (i32 &lt;=&gt; int32_t), the
314//! following common types may be used in the fields of shared structs and the
315//! arguments and returns of functions.
David Tolnay7db73692019-10-20 14:51:12 -0400316//!
317//! <table>
318//! <tr><th>name in Rust</th><th>name in C++</th><th>restrictions</th></tr>
David Tolnay750755e2020-03-01 13:04:08 -0800319//! <tr><td>String</td><td>rust::String</td><td></td></tr>
320//! <tr><td>&amp;str</td><td>rust::Str</td><td></td></tr>
David Tolnayefe81052020-04-14 16:28:24 -0700321//! <tr><td>&amp;[u8]</td><td>rust::Slice&lt;uint8_t&gt;</td><td><sup><i>arbitrary &amp;[T] not implemented yet</i></sup></td></tr>
David Tolnayf51dc4d2020-03-12 00:45:30 -0700322//! <tr><td><a href="https://docs.rs/cxx/0.2/cxx/struct.CxxString.html">CxxString</a></td><td>std::string</td><td><sup><i>cannot be passed by value</i></sup></td></tr>
David Tolnay750755e2020-03-01 13:04:08 -0800323//! <tr><td>Box&lt;T&gt;</td><td>rust::Box&lt;T&gt;</td><td><sup><i>cannot hold opaque C++ type</i></sup></td></tr>
David Tolnayf51dc4d2020-03-12 00:45:30 -0700324//! <tr><td><a href="https://docs.rs/cxx/0.2/cxx/struct.UniquePtr.html">UniquePtr&lt;T&gt;</a></td><td>std::unique_ptr&lt;T&gt;</td><td><sup><i>cannot hold opaque Rust type</i></sup></td></tr>
David Tolnayaddc7482020-03-29 22:19:44 -0700325//! <tr><td>fn(T, U) -&gt; V</td><td>rust::Fn&lt;V(T, U)&gt;</td><td><sup><i>only passing from Rust to C++ is implemented so far</i></sup></td></tr>
David Tolnay31b5aad2020-04-10 19:35:47 -0700326//! <tr><td>Result&lt;T&gt;</td><td>throw/catch</td><td><sup><i>allowed as return type only</i></sup></td></tr>
David Tolnay7db73692019-10-20 14:51:12 -0400327//! </table>
328//!
David Tolnay736cbca2020-03-11 16:49:18 -0700329//! The C++ API of the `rust` namespace is defined by the *include/cxx.h* file
David Tolnayd763f182020-03-12 00:50:19 -0700330//! in [https://github.com/dtolnay/cxx]. You will need to include this header in
David Tolnay736cbca2020-03-11 16:49:18 -0700331//! your C++ code when working with those types.
David Tolnay7db73692019-10-20 14:51:12 -0400332//!
333//! The following types are intended to be supported "soon" but are just not
334//! implemented yet. I don't expect any of these to be hard to make work but
335//! it's a matter of designing a nice API for each in its non-native language.
336//!
337//! <table>
338//! <tr><th>name in Rust</th><th>name in C++</th></tr>
David Tolnay84f232e2020-01-08 12:22:56 -0800339//! <tr><td>Vec&lt;T&gt;</td><td><sup><i>tbd</i></sup></td></tr>
340//! <tr><td>BTreeMap&lt;K, V&gt;</td><td><sup><i>tbd</i></sup></td></tr>
341//! <tr><td>HashMap&lt;K, V&gt;</td><td><sup><i>tbd</i></sup></td></tr>
David Tolnay239d05f2020-03-13 01:36:50 -0700342//! <tr><td>Arc&lt;T&gt;</td><td><sup><i>tbd</i></sup></td></tr>
David Tolnay84f232e2020-01-08 12:22:56 -0800343//! <tr><td><sup><i>tbd</i></sup></td><td>std::vector&lt;T&gt;</td></tr>
344//! <tr><td><sup><i>tbd</i></sup></td><td>std::map&lt;K, V&gt;</td></tr>
345//! <tr><td><sup><i>tbd</i></sup></td><td>std::unordered_map&lt;K, V&gt;</td></tr>
David Tolnay239d05f2020-03-13 01:36:50 -0700346//! <tr><td><sup><i>tbd</i></sup></td><td>std::shared_ptr&lt;T&gt;</td></tr>
David Tolnay7db73692019-10-20 14:51:12 -0400347//! </table>
David Tolnayd763f182020-03-12 00:50:19 -0700348//!
349//! [https://github.com/dtolnay/cxx]: https://github.com/dtolnay/cxx
David Tolnay7db73692019-10-20 14:51:12 -0400350
David Tolnay4272d982020-04-14 16:57:00 -0700351#![doc(html_root_url = "https://docs.rs/cxx/0.2.9")]
David Tolnay7db73692019-10-20 14:51:12 -0400352#![deny(improper_ctypes)]
353#![allow(
David Tolnay4bc98152020-04-09 23:24:01 -0700354 clippy::cognitive_complexity,
David Tolnayd2bb3da2020-03-18 17:19:39 -0700355 clippy::declare_interior_mutable_const,
David Tolnay30d214c2020-03-15 23:54:34 -0700356 clippy::inherent_to_string,
David Tolnay7db73692019-10-20 14:51:12 -0400357 clippy::large_enum_variant,
358 clippy::missing_safety_doc,
359 clippy::module_inception,
David Tolnay30d214c2020-03-15 23:54:34 -0700360 clippy::needless_doctest_main,
David Tolnay7db73692019-10-20 14:51:12 -0400361 clippy::new_without_default,
362 clippy::or_fun_call,
363 clippy::ptr_arg,
364 clippy::toplevel_ref_arg,
David Tolnay7db73692019-10-20 14:51:12 -0400365 clippy::useless_let_if_seq
366)]
367
David Tolnayaf60e232020-01-24 15:22:09 -0800368extern crate link_cplusplus;
369
David Tolnayda5bd272020-03-16 21:53:22 -0700370#[macro_use]
371mod assert;
372
David Tolnay7db73692019-10-20 14:51:12 -0400373mod cxx_string;
374mod error;
David Tolnayebef4a22020-03-17 15:33:47 -0700375mod exception;
David Tolnay75dca2e2020-03-25 20:17:52 -0700376mod function;
David Tolnay7db73692019-10-20 14:51:12 -0400377mod gen;
378mod opaque;
379mod paths;
David Tolnay486b6ec2020-03-17 01:19:57 -0700380mod result;
Adrian Taylorf5dd5522020-04-13 16:50:14 -0700381mod rust_sliceu8;
David Tolnay7db73692019-10-20 14:51:12 -0400382mod rust_str;
383mod rust_string;
384mod syntax;
385mod unique_ptr;
386mod unwind;
387
388pub use crate::cxx_string::CxxString;
David Tolnayebef4a22020-03-17 15:33:47 -0700389pub use crate::exception::Exception;
David Tolnay7db73692019-10-20 14:51:12 -0400390pub use crate::unique_ptr::UniquePtr;
391pub use cxxbridge_macro::bridge;
392
393// Not public API.
394#[doc(hidden)]
395pub mod private {
David Tolnay75dca2e2020-03-25 20:17:52 -0700396 pub use crate::function::FatFunction;
David Tolnay7db73692019-10-20 14:51:12 -0400397 pub use crate::opaque::Opaque;
David Tolnay486b6ec2020-03-17 01:19:57 -0700398 pub use crate::result::{r#try, Result};
Adrian Taylorf5dd5522020-04-13 16:50:14 -0700399 pub use crate::rust_sliceu8::RustSliceU8;
David Tolnay7db73692019-10-20 14:51:12 -0400400 pub use crate::rust_str::RustStr;
401 pub use crate::rust_string::RustString;
402 pub use crate::unique_ptr::UniquePtrTarget;
403 pub use crate::unwind::catch_unwind;
404}
405
406use crate::error::Result;
David Tolnay33d30292020-03-18 18:02:02 -0700407use crate::gen::Opt;
David Tolnay366ef8b2020-01-26 14:15:59 -0800408use anyhow::anyhow;
David Tolnay7db73692019-10-20 14:51:12 -0400409use std::fs;
410use std::io::{self, Write};
411use std::path::Path;
412use std::process;
413
414/// The CXX code generator for constructing and compiling C++ code.
415///
416/// This is intended to be used from Cargo build scripts to execute CXX's
417/// C++ code generator, set up any additional compiler flags depending on
418/// the use case, and make the C++ compiler invocation.
419///
420/// <br>
421///
422/// # Example
423///
424/// Example of a canonical Cargo build script that builds a CXX bridge:
425///
426/// ```no_run
427/// // build.rs
428///
429/// fn main() {
430/// cxx::Build::new()
431/// .bridge("src/main.rs")
432/// .file("../demo-cxx/demo.cc")
433/// .flag("-std=c++11")
434/// .compile("cxxbridge-demo");
435///
436/// println!("cargo:rerun-if-changed=src/main.rs");
437/// println!("cargo:rerun-if-changed=../demo-cxx/demo.h");
438/// println!("cargo:rerun-if-changed=../demo-cxx/demo.cc");
439/// }
440/// ```
441///
442/// A runnable working setup with this build script is shown in the
David Tolnayd763f182020-03-12 00:50:19 -0700443/// *demo-rs* and *demo-cxx* directories of [https://github.com/dtolnay/cxx].
444///
445/// [https://github.com/dtolnay/cxx]: https://github.com/dtolnay/cxx
David Tolnay7db73692019-10-20 14:51:12 -0400446///
447/// <br>
448///
449/// # Alternatives
450///
451/// For use in non-Cargo builds like Bazel or Buck, CXX provides an
452/// alternate way of invoking the C++ code generator as a standalone command
453/// line tool. The tool is packaged as the `cxxbridge-cmd` crate.
454///
455/// ```bash
456/// $ cargo install cxxbridge-cmd # or build it from the repo
457///
458/// $ cxxbridge src/main.rs --header > path/to/mybridge.h
459/// $ cxxbridge src/main.rs > path/to/mybridge.cc
460/// ```
461#[must_use]
462pub struct Build {
463 _private: (),
464}
465
466impl Build {
467 /// Begin with a [`cc::Build`] in its default configuration.
468 pub fn new() -> Self {
469 Build { _private: () }
470 }
471
472 /// This returns a [`cc::Build`] on which you should continue to set up
473 /// any additional source files or compiler flags, and lastly call its
474 /// [`compile`] method to execute the C++ build.
475 ///
476 /// [`compile`]: https://docs.rs/cc/1.0.49/cc/struct.Build.html#method.compile
477 #[must_use]
478 pub fn bridge(&self, rust_source_file: impl AsRef<Path>) -> cc::Build {
479 match try_generate_bridge(rust_source_file.as_ref()) {
480 Ok(build) => build,
481 Err(err) => {
David Tolnay366ef8b2020-01-26 14:15:59 -0800482 let _ = writeln!(io::stderr(), "\n\ncxxbridge error: {:?}\n\n", anyhow!(err));
David Tolnay7db73692019-10-20 14:51:12 -0400483 process::exit(1);
484 }
485 }
486 }
487}
488
489fn try_generate_bridge(rust_source_file: &Path) -> Result<cc::Build> {
David Tolnay33d30292020-03-18 18:02:02 -0700490 let header = gen::do_generate_header(rust_source_file, Opt::default());
David Tolnay7db73692019-10-20 14:51:12 -0400491 let header_path = paths::out_with_extension(rust_source_file, ".h")?;
492 fs::create_dir_all(header_path.parent().unwrap())?;
493 fs::write(&header_path, header)?;
494 paths::symlink_header(&header_path, rust_source_file);
495
David Tolnay33d30292020-03-18 18:02:02 -0700496 let bridge = gen::do_generate_bridge(rust_source_file, Opt::default());
David Tolnay7db73692019-10-20 14:51:12 -0400497 let bridge_path = paths::out_with_extension(rust_source_file, ".cc")?;
498 fs::write(&bridge_path, bridge)?;
499 let mut build = paths::cc_build();
500 build.file(&bridge_path);
501
David Tolnay736cbca2020-03-11 16:49:18 -0700502 let ref cxx_h = paths::include_dir()?.join("rust").join("cxx.h");
503 let _ = fs::create_dir_all(cxx_h.parent().unwrap());
504 let _ = fs::remove_file(cxx_h);
505 let _ = fs::write(cxx_h, gen::include::HEADER);
David Tolnayc43627a2020-01-28 00:50:25 -0800506
David Tolnay7db73692019-10-20 14:51:12 -0400507 Ok(build)
508}