• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 //! The CXX code generator for constructing and compiling C++ code.
2 //!
3 //! This is intended to be used from Cargo build scripts to execute CXX's
4 //! C++ code generator, set up any additional compiler flags depending on
5 //! the use case, and make the C++ compiler invocation.
6 //!
7 //! <br>
8 //!
9 //! # Example
10 //!
11 //! Example of a canonical Cargo build script that builds a CXX bridge:
12 //!
13 //! ```no_run
14 //! // build.rs
15 //!
16 //! fn main() {
17 //!     cxx_build::bridge("src/main.rs")
18 //!         .file("src/demo.cc")
19 //!         .flag_if_supported("-std=c++11")
20 //!         .compile("cxxbridge-demo");
21 //!
22 //!     println!("cargo:rerun-if-changed=src/main.rs");
23 //!     println!("cargo:rerun-if-changed=src/demo.cc");
24 //!     println!("cargo:rerun-if-changed=include/demo.h");
25 //! }
26 //! ```
27 //!
28 //! A runnable working setup with this build script is shown in the *demo*
29 //! directory of [https://github.com/dtolnay/cxx].
30 //!
31 //! [https://github.com/dtolnay/cxx]: https://github.com/dtolnay/cxx
32 //!
33 //! <br>
34 //!
35 //! # Alternatives
36 //!
37 //! For use in non-Cargo builds like Bazel or Buck, CXX provides an
38 //! alternate way of invoking the C++ code generator as a standalone command
39 //! line tool. The tool is packaged as the `cxxbridge-cmd` crate.
40 //!
41 //! ```bash
42 //! $ cargo install cxxbridge-cmd  # or build it from the repo
43 //!
44 //! $ cxxbridge src/main.rs --header > path/to/mybridge.h
45 //! $ cxxbridge src/main.rs > path/to/mybridge.cc
46 //! ```
47 
48 #![allow(
49     clippy::cast_sign_loss,
50     clippy::default_trait_access,
51     clippy::doc_markdown,
52     clippy::drop_copy,
53     clippy::enum_glob_use,
54     clippy::if_same_then_else,
55     clippy::inherent_to_string,
56     clippy::items_after_statements,
57     clippy::let_underscore_drop,
58     clippy::match_bool,
59     clippy::match_on_vec_items,
60     clippy::match_same_arms,
61     clippy::module_name_repetitions,
62     clippy::needless_doctest_main,
63     clippy::needless_pass_by_value,
64     clippy::new_without_default,
65     clippy::nonminimal_bool,
66     clippy::option_if_let_else,
67     clippy::or_fun_call,
68     clippy::redundant_else,
69     clippy::shadow_unrelated,
70     clippy::similar_names,
71     clippy::single_match_else,
72     clippy::struct_excessive_bools,
73     clippy::too_many_arguments,
74     clippy::too_many_lines,
75     clippy::toplevel_ref_arg,
76     clippy::upper_case_acronyms,
77     // clippy bug: https://github.com/rust-lang/rust-clippy/issues/6983
78     clippy::wrong_self_convention
79 )]
80 
81 mod cfg;
82 mod deps;
83 mod error;
84 mod gen;
85 mod intern;
86 mod out;
87 mod paths;
88 mod syntax;
89 mod target;
90 mod vec;
91 
92 use crate::deps::{Crate, HeaderDir};
93 use crate::error::{Error, Result};
94 use crate::gen::error::report;
95 use crate::gen::Opt;
96 use crate::paths::PathExt;
97 use crate::syntax::map::{Entry, UnorderedMap};
98 use crate::target::TargetDir;
99 use cc::Build;
100 use std::collections::BTreeSet;
101 use std::env;
102 use std::ffi::{OsStr, OsString};
103 use std::io::{self, Write};
104 use std::iter;
105 use std::path::{Path, PathBuf};
106 use std::process;
107 
108 pub use crate::cfg::{Cfg, CFG};
109 
110 /// This returns a [`cc::Build`] on which you should continue to set up any
111 /// additional source files or compiler flags, and lastly call its [`compile`]
112 /// method to execute the C++ build.
113 ///
114 /// [`compile`]: https://docs.rs/cc/1.0.49/cc/struct.Build.html#method.compile
115 #[must_use]
bridge(rust_source_file: impl AsRef<Path>) -> Build116 pub fn bridge(rust_source_file: impl AsRef<Path>) -> Build {
117     bridges(iter::once(rust_source_file))
118 }
119 
120 /// `cxx_build::bridge` but for when more than one file contains a
121 /// #\[cxx::bridge\] module.
122 ///
123 /// ```no_run
124 /// let source_files = vec!["src/main.rs", "src/path/to/other.rs"];
125 /// cxx_build::bridges(source_files)
126 ///     .file("src/demo.cc")
127 ///     .flag_if_supported("-std=c++11")
128 ///     .compile("cxxbridge-demo");
129 /// ```
130 #[must_use]
bridges(rust_source_files: impl IntoIterator<Item = impl AsRef<Path>>) -> Build131 pub fn bridges(rust_source_files: impl IntoIterator<Item = impl AsRef<Path>>) -> Build {
132     let ref mut rust_source_files = rust_source_files.into_iter();
133     build(rust_source_files).unwrap_or_else(|err| {
134         let _ = writeln!(io::stderr(), "\n\ncxxbridge error: {}\n\n", report(err));
135         process::exit(1);
136     })
137 }
138 
139 struct Project {
140     include_prefix: PathBuf,
141     manifest_dir: PathBuf,
142     // The `links = "..."` value from Cargo.toml.
143     links_attribute: Option<OsString>,
144     // Output directory as received from Cargo.
145     out_dir: PathBuf,
146     // Directory into which to symlink all generated code.
147     //
148     // This is *not* used for an #include path, only as a debugging convenience.
149     // Normally available at target/cxxbridge/ if we are able to know where the
150     // target dir is, otherwise under a common scratch dir.
151     //
152     // The reason this isn't the #include dir is that we do not want builds to
153     // have access to headers from arbitrary other parts of the dependency
154     // graph. Using a global directory for all builds would be both a race
155     // condition depending on what order Cargo randomly executes the build
156     // scripts, as well as semantically undesirable for builds not to have to
157     // declare their real dependencies.
158     shared_dir: PathBuf,
159 }
160 
161 impl Project {
init() -> Result<Self>162     fn init() -> Result<Self> {
163         let include_prefix = Path::new(CFG.include_prefix);
164         assert!(include_prefix.is_relative());
165         let include_prefix = include_prefix.components().collect();
166 
167         let links_attribute = env::var_os("CARGO_MANIFEST_LINKS");
168 
169         let manifest_dir = paths::manifest_dir()?;
170         let out_dir = paths::out_dir()?;
171 
172         let shared_dir = match target::find_target_dir(&out_dir) {
173             TargetDir::Path(target_dir) => target_dir.join("cxxbridge"),
174             TargetDir::Unknown => scratch::path("cxxbridge"),
175         };
176 
177         Ok(Project {
178             include_prefix,
179             manifest_dir,
180             links_attribute,
181             out_dir,
182             shared_dir,
183         })
184     }
185 }
186 
187 // We lay out the OUT_DIR as follows. Everything is namespaced under a cxxbridge
188 // subdirectory to avoid stomping on other things that the caller's build script
189 // might be doing inside OUT_DIR.
190 //
191 //     $OUT_DIR/
192 //        cxxbridge/
193 //           crate/
194 //              $CARGO_PKG_NAME -> $CARGO_MANIFEST_DIR
195 //           include/
196 //              rust/
197 //                 cxx.h
198 //              $CARGO_PKG_NAME/
199 //                 .../
200 //                    lib.rs.h
201 //           sources/
202 //              $CARGO_PKG_NAME/
203 //                 .../
204 //                    lib.rs.cc
205 //
206 // The crate/ and include/ directories are placed on the #include path for the
207 // current build as well as for downstream builds that have a direct dependency
208 // on the current crate.
build(rust_source_files: &mut dyn Iterator<Item = impl AsRef<Path>>) -> Result<Build>209 fn build(rust_source_files: &mut dyn Iterator<Item = impl AsRef<Path>>) -> Result<Build> {
210     let ref prj = Project::init()?;
211     validate_cfg(prj)?;
212     let this_crate = make_this_crate(prj)?;
213 
214     let mut build = Build::new();
215     build.cpp(true);
216     build.cpp_link_stdlib(None); // linked via link-cplusplus crate
217 
218     for path in rust_source_files {
219         generate_bridge(prj, &mut build, path.as_ref())?;
220     }
221 
222     this_crate.print_to_cargo();
223     eprintln!("\nCXX include path:");
224     for header_dir in this_crate.header_dirs {
225         build.include(&header_dir.path);
226         if header_dir.exported {
227             eprintln!("  {}", header_dir.path.display());
228         } else {
229             eprintln!("  {} (private)", header_dir.path.display());
230         }
231     }
232 
233     Ok(build)
234 }
235 
validate_cfg(prj: &Project) -> Result<()>236 fn validate_cfg(prj: &Project) -> Result<()> {
237     for exported_dir in &CFG.exported_header_dirs {
238         if !exported_dir.is_absolute() {
239             return Err(Error::ExportedDirNotAbsolute(exported_dir));
240         }
241     }
242 
243     for prefix in &CFG.exported_header_prefixes {
244         if prefix.is_empty() {
245             return Err(Error::ExportedEmptyPrefix);
246         }
247     }
248 
249     if prj.links_attribute.is_none() {
250         if !CFG.exported_header_dirs.is_empty() {
251             return Err(Error::ExportedDirsWithoutLinks);
252         }
253         if !CFG.exported_header_prefixes.is_empty() {
254             return Err(Error::ExportedPrefixesWithoutLinks);
255         }
256         if !CFG.exported_header_links.is_empty() {
257             return Err(Error::ExportedLinksWithoutLinks);
258         }
259     }
260 
261     Ok(())
262 }
263 
make_this_crate(prj: &Project) -> Result<Crate>264 fn make_this_crate(prj: &Project) -> Result<Crate> {
265     let crate_dir = make_crate_dir(prj);
266     let include_dir = make_include_dir(prj)?;
267 
268     let mut this_crate = Crate {
269         include_prefix: Some(prj.include_prefix.clone()),
270         links: prj.links_attribute.clone(),
271         header_dirs: Vec::new(),
272     };
273 
274     // The generated code directory (include_dir) is placed in front of
275     // crate_dir on the include line so that `#include "path/to/file.rs"` from
276     // C++ "magically" works and refers to the API generated from that Rust
277     // source file.
278     this_crate.header_dirs.push(HeaderDir {
279         exported: true,
280         path: include_dir,
281     });
282 
283     this_crate.header_dirs.push(HeaderDir {
284         exported: true,
285         path: crate_dir,
286     });
287 
288     for exported_dir in &CFG.exported_header_dirs {
289         this_crate.header_dirs.push(HeaderDir {
290             exported: true,
291             path: PathBuf::from(exported_dir),
292         });
293     }
294 
295     let mut header_dirs_index = UnorderedMap::new();
296     let mut used_header_links = BTreeSet::new();
297     let mut used_header_prefixes = BTreeSet::new();
298     for krate in deps::direct_dependencies() {
299         let mut is_link_exported = || match &krate.links {
300             None => false,
301             Some(links_attribute) => CFG.exported_header_links.iter().any(|&exported| {
302                 let matches = links_attribute == exported;
303                 if matches {
304                     used_header_links.insert(exported);
305                 }
306                 matches
307             }),
308         };
309 
310         let mut is_prefix_exported = || match &krate.include_prefix {
311             None => false,
312             Some(include_prefix) => CFG.exported_header_prefixes.iter().any(|&exported| {
313                 let matches = include_prefix.starts_with(exported);
314                 if matches {
315                     used_header_prefixes.insert(exported);
316                 }
317                 matches
318             }),
319         };
320 
321         let exported = is_link_exported() || is_prefix_exported();
322 
323         for dir in krate.header_dirs {
324             // Deduplicate dirs reachable via multiple transitive dependencies.
325             match header_dirs_index.entry(dir.path.clone()) {
326                 Entry::Vacant(entry) => {
327                     entry.insert(this_crate.header_dirs.len());
328                     this_crate.header_dirs.push(HeaderDir {
329                         exported,
330                         path: dir.path,
331                     });
332                 }
333                 Entry::Occupied(entry) => {
334                     let index = *entry.get();
335                     this_crate.header_dirs[index].exported |= exported;
336                 }
337             }
338         }
339     }
340 
341     if let Some(unused) = CFG
342         .exported_header_links
343         .iter()
344         .find(|&exported| !used_header_links.contains(exported))
345     {
346         return Err(Error::UnusedExportedLinks(unused));
347     }
348 
349     if let Some(unused) = CFG
350         .exported_header_prefixes
351         .iter()
352         .find(|&exported| !used_header_prefixes.contains(exported))
353     {
354         return Err(Error::UnusedExportedPrefix(unused));
355     }
356 
357     Ok(this_crate)
358 }
359 
make_crate_dir(prj: &Project) -> PathBuf360 fn make_crate_dir(prj: &Project) -> PathBuf {
361     if prj.include_prefix.as_os_str().is_empty() {
362         return prj.manifest_dir.clone();
363     }
364     let crate_dir = prj.out_dir.join("cxxbridge").join("crate");
365     let ref link = crate_dir.join(&prj.include_prefix);
366     let ref manifest_dir = prj.manifest_dir;
367     if out::symlink_dir(manifest_dir, link).is_err() && cfg!(not(unix)) {
368         let cachedir_tag = "\
369         Signature: 8a477f597d28d172789f06886806bc55\n\
370         # This file is a cache directory tag created by cxx.\n\
371         # For information about cache directory tags see https://bford.info/cachedir/\n";
372         let _ = out::write(crate_dir.join("CACHEDIR.TAG"), cachedir_tag.as_bytes());
373         let max_depth = 6;
374         best_effort_copy_headers(manifest_dir, link, max_depth);
375     }
376     crate_dir
377 }
378 
make_include_dir(prj: &Project) -> Result<PathBuf>379 fn make_include_dir(prj: &Project) -> Result<PathBuf> {
380     let include_dir = prj.out_dir.join("cxxbridge").join("include");
381     let cxx_h = include_dir.join("rust").join("cxx.h");
382     let ref shared_cxx_h = prj.shared_dir.join("rust").join("cxx.h");
383     if let Some(ref original) = env::var_os("DEP_CXXBRIDGE1_HEADER") {
384         out::symlink_file(original, cxx_h)?;
385         out::symlink_file(original, shared_cxx_h)?;
386     } else {
387         out::write(shared_cxx_h, gen::include::HEADER.as_bytes())?;
388         out::symlink_file(shared_cxx_h, cxx_h)?;
389     }
390     Ok(include_dir)
391 }
392 
generate_bridge(prj: &Project, build: &mut Build, rust_source_file: &Path) -> Result<()>393 fn generate_bridge(prj: &Project, build: &mut Build, rust_source_file: &Path) -> Result<()> {
394     let opt = Opt {
395         allow_dot_includes: false,
396         ..Opt::default()
397     };
398     let generated = gen::generate_from_path(rust_source_file, &opt);
399     let ref rel_path = paths::local_relative_path(rust_source_file);
400 
401     let cxxbridge = prj.out_dir.join("cxxbridge");
402     let include_dir = cxxbridge.join("include").join(&prj.include_prefix);
403     let sources_dir = cxxbridge.join("sources").join(&prj.include_prefix);
404 
405     let ref rel_path_h = rel_path.with_appended_extension(".h");
406     let ref header_path = include_dir.join(rel_path_h);
407     out::write(header_path, &generated.header)?;
408 
409     let ref link_path = include_dir.join(rel_path);
410     let _ = out::symlink_file(header_path, link_path);
411 
412     let ref rel_path_cc = rel_path.with_appended_extension(".cc");
413     let ref implementation_path = sources_dir.join(rel_path_cc);
414     out::write(implementation_path, &generated.implementation)?;
415     build.file(implementation_path);
416 
417     let shared_h = prj.shared_dir.join(&prj.include_prefix).join(rel_path_h);
418     let shared_cc = prj.shared_dir.join(&prj.include_prefix).join(rel_path_cc);
419     let _ = out::symlink_file(header_path, shared_h);
420     let _ = out::symlink_file(implementation_path, shared_cc);
421     Ok(())
422 }
423 
best_effort_copy_headers(src: &Path, dst: &Path, max_depth: usize)424 fn best_effort_copy_headers(src: &Path, dst: &Path, max_depth: usize) {
425     // Not using crate::gen::fs because we aren't reporting the errors.
426     use std::fs;
427 
428     let mut dst_created = false;
429     let mut entries = match fs::read_dir(src) {
430         Ok(entries) => entries,
431         Err(_) => return,
432     };
433 
434     while let Some(Ok(entry)) = entries.next() {
435         let file_name = entry.file_name();
436         if file_name.to_string_lossy().starts_with('.') {
437             continue;
438         }
439         match entry.file_type() {
440             Ok(file_type) if file_type.is_dir() && max_depth > 0 => {
441                 let src = entry.path();
442                 if src.join("Cargo.toml").exists() || src.join("CACHEDIR.TAG").exists() {
443                     continue;
444                 }
445                 let dst = dst.join(file_name);
446                 best_effort_copy_headers(&src, &dst, max_depth - 1);
447             }
448             Ok(file_type) if file_type.is_file() => {
449                 let src = entry.path();
450                 match src.extension().and_then(OsStr::to_str) {
451                     Some("h") | Some("hh") | Some("hpp") => {}
452                     _ => continue,
453                 }
454                 if !dst_created && fs::create_dir_all(dst).is_err() {
455                     return;
456                 }
457                 dst_created = true;
458                 let dst = dst.join(file_name);
459                 let _ = fs::remove_file(&dst);
460                 let _ = fs::copy(src, dst);
461             }
462             _ => {}
463         }
464     }
465 }
466 
env_os(key: impl AsRef<OsStr>) -> Result<OsString>467 fn env_os(key: impl AsRef<OsStr>) -> Result<OsString> {
468     let key = key.as_ref();
469     env::var_os(key).ok_or_else(|| Error::NoEnv(key.to_owned()))
470 }
471