-
Notifications
You must be signed in to change notification settings - Fork 350
/
Copy pathlib.rs
304 lines (278 loc) · 10.7 KB
/
lib.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
//! The CXX code generator for constructing and compiling C++ code.
//!
//! This is intended to be used from Cargo build scripts to execute CXX's
//! C++ code generator, set up any additional compiler flags depending on
//! the use case, and make the C++ compiler invocation.
//!
//! <br>
//!
//! # Example
//!
//! Example of a canonical Cargo build script that builds a CXX bridge:
//!
//! ```no_run
//! // build.rs
//!
//! fn main() {
//! cxx_build::bridge("src/main.rs")
//! .file("src/demo.cc")
//! .flag_if_supported("-std=c++11")
//! .compile("cxxbridge-demo");
//!
//! println!("cargo:rerun-if-changed=src/main.rs");
//! println!("cargo:rerun-if-changed=src/demo.cc");
//! println!("cargo:rerun-if-changed=include/demo.h");
//! }
//! ```
//!
//! A runnable working setup with this build script is shown in the *demo*
//! directory of [https://github.com/dtolnay/cxx].
//!
//! [https://github.com/dtolnay/cxx]: https://github.com/dtolnay/cxx
//!
//! <br>
//!
//! # Alternatives
//!
//! For use in non-Cargo builds like Bazel or Buck, CXX provides an
//! alternate way of invoking the C++ code generator as a standalone command
//! line tool. The tool is packaged as the `cxxbridge-cmd` crate.
//!
//! ```bash
//! $ cargo install cxxbridge-cmd # or build it from the repo
//!
//! $ cxxbridge src/main.rs --header > path/to/mybridge.h
//! $ cxxbridge src/main.rs > path/to/mybridge.cc
//! ```
#![allow(
clippy::drop_copy,
clippy::inherent_to_string,
clippy::needless_doctest_main,
clippy::new_without_default,
clippy::or_fun_call,
clippy::toplevel_ref_arg
)]
mod cfg;
mod error;
mod gen;
mod out;
mod paths;
mod syntax;
mod target;
use crate::error::{Error, Result};
use crate::gen::error::report;
use crate::gen::Opt;
use crate::paths::PathExt;
use crate::target::TargetDir;
use cc::Build;
use std::collections::BTreeMap;
use std::env;
use std::ffi::{OsStr, OsString};
use std::io::{self, Write};
use std::iter;
use std::path::{Path, PathBuf};
use std::process;
pub use crate::cfg::{Cfg, CFG};
/// This returns a [`cc::Build`] on which you should continue to set up any
/// additional source files or compiler flags, and lastly call its [`compile`]
/// method to execute the C++ build.
///
/// [`compile`]: https://docs.rs/cc/1.0.49/cc/struct.Build.html#method.compile
#[must_use]
pub fn bridge(rust_source_file: impl AsRef<Path>) -> Build {
bridges(iter::once(rust_source_file))
}
/// `cxx_build::bridge` but for when more than one file contains a
/// #\[cxx::bridge\] module.
///
/// ```no_run
/// let source_files = vec!["src/main.rs", "src/path/to/other.rs"];
/// cxx_build::bridges(source_files)
/// .file("src/demo.cc")
/// .flag_if_supported("-std=c++11")
/// .compile("cxxbridge-demo");
/// ```
#[must_use]
pub fn bridges(rust_source_files: impl IntoIterator<Item = impl AsRef<Path>>) -> Build {
let ref mut rust_source_files = rust_source_files.into_iter();
build(rust_source_files).unwrap_or_else(|err| {
let _ = writeln!(io::stderr(), "\n\ncxxbridge error: {}\n\n", report(err));
process::exit(1);
})
}
struct Project {
include_prefix: PathBuf,
manifest_dir: PathBuf,
// Output directory as received from Cargo.
out_dir: PathBuf,
// Directory into which to symlink all generated code.
//
// This is *not* used for an #include path, only as a debugging convenience.
// Normally available at target/cxxbridge/ if we are able to know where the
// target dir is, otherwise under a common scratch dir.
//
// The reason this isn't the #include dir is that we do not want builds to
// have access to headers from arbitrary other parts of the dependency
// graph. Using a global directory for all builds would be both a race
// condition depending on what order Cargo randomly executes the build
// scripts, as well as semantically undesirable for builds not to have to
// declare their real dependencies.
shared_dir: PathBuf,
}
impl Project {
fn init() -> Result<Self> {
let include_prefix = Path::new(CFG.include_prefix);
assert!(include_prefix.is_relative());
let include_prefix = include_prefix.components().collect();
let manifest_dir = paths::manifest_dir()?;
let out_dir = paths::out_dir()?;
let shared_dir = match target::find_target_dir(&out_dir) {
TargetDir::Path(target_dir) => target_dir.join("cxxbridge"),
TargetDir::Unknown => scratch::path("cxxbridge"),
};
Ok(Project {
include_prefix,
manifest_dir,
out_dir,
shared_dir,
})
}
}
// We lay out the OUT_DIR as follows. Everything is namespaced under a cxxbridge
// subdirectory to avoid stomping on other things that the caller's build script
// might be doing inside OUT_DIR.
//
// $OUT_DIR/
// cxxbridge/
// crate/
// $CARGO_PKG_NAME -> $CARGO_MANIFEST_DIR
// include/
// rust/
// cxx.h
// $CARGO_PKG_NAME/
// .../
// lib.rs.h
// sources/
// $CARGO_PKG_NAME/
// .../
// lib.rs.cc
//
// The crate/ and include/ directories are placed on the #include path for the
// current build as well as for downstream builds that have a direct dependency
// on the current crate.
fn build(rust_source_files: &mut dyn Iterator<Item = impl AsRef<Path>>) -> Result<Build> {
let ref prj = Project::init()?;
let ref crate_dir = make_crate_dir(prj);
let ref include_dir = make_include_dir(prj)?;
let mut build = Build::new();
build.cpp(true);
build.cpp_link_stdlib(None); // linked via link-cplusplus crate
for path in rust_source_files {
generate_bridge(prj, &mut build, path.as_ref())?;
}
eprintln!("\nCXX include path:");
build.include(include_dir);
eprintln!(" {}", include_dir.display());
if let Some(crate_dir) = crate_dir {
// Placed after the generated code directory (include_dir) on the
// include line so that `#include "path/to/file.rs"` from C++
// "magically" works and refers to the API generated from that Rust
// source file.
build.include(crate_dir);
eprintln!(" {}", crate_dir.display());
}
for dep in env_include_dirs() {
build.include(&dep);
eprintln!(" {}", dep.display());
}
Ok(build)
}
fn env_include_dirs() -> impl Iterator<Item = PathBuf> {
let mut env_include_dirs = BTreeMap::new();
for (k, v) in env::vars_os() {
let mut k = k.to_string_lossy().into_owned();
// Only variables set from a build script of direct dependencies are
// observable. That's exactly what we want! Your crate needs to declare
// a direct dependency on the other crate in order to be able to
// #include its headers.
//
// Also, they're only observable if the dependency's manifest contains a
// `links` key. This is important because Cargo imposes no ordering on
// the execution of build scripts without a `links` key. When exposing a
// generated header for the current crate to #include, we need to be
// sure the dependency's build script has already executed and emitted
// that generated header.
//
// References:
// - https://doc.rust-lang.org/cargo/reference/build-scripts.html#the-links-manifest-key
// - https://doc.rust-lang.org/cargo/reference/build-script-examples.html#using-another-sys-crate
if k.starts_with("DEP_") {
if k.ends_with("_CXXBRIDGE_INCLUDE") {
// Tweak to ensure sorted before the other one, for the same
// reason as the comment on ordering of include_dir vs crate_dir
// above.
k.replace_range(k.len() - "INCLUDE".len().., "0");
env_include_dirs.insert(k, PathBuf::from(v));
} else if k.ends_with("_CXXBRIDGE_CRATE") {
k.replace_range(k.len() - "CRATE".len().., "1");
env_include_dirs.insert(k, PathBuf::from(v));
}
}
}
env_include_dirs.into_iter().map(|entry| entry.1)
}
fn make_crate_dir(prj: &Project) -> Option<PathBuf> {
if prj.include_prefix.as_os_str().is_empty() {
let crate_dir = prj.manifest_dir.clone();
println!("cargo:CXXBRIDGE_CRATE={}", crate_dir.to_string_lossy());
return Some(crate_dir);
}
let crate_dir = prj.out_dir.join("cxxbridge").join("crate");
let link = crate_dir.join(&prj.include_prefix);
if out::symlink_dir(&prj.manifest_dir, link).is_ok() {
println!("cargo:CXXBRIDGE_CRATE={}", crate_dir.to_string_lossy());
Some(crate_dir)
} else {
None
}
}
fn make_include_dir(prj: &Project) -> Result<PathBuf> {
let include_dir = prj.out_dir.join("cxxbridge").join("include");
let cxx_h = include_dir.join("rust").join("cxx.h");
let ref shared_cxx_h = prj.shared_dir.join("rust").join("cxx.h");
if let Some(ref original) = env::var_os("DEP_CXXBRIDGE05_HEADER") {
out::symlink_file(original, cxx_h)?;
out::symlink_file(original, shared_cxx_h)?;
} else {
out::write(shared_cxx_h, gen::include::HEADER.as_bytes())?;
out::symlink_file(shared_cxx_h, cxx_h)?;
}
println!("cargo:CXXBRIDGE_INCLUDE={}", include_dir.to_string_lossy());
Ok(include_dir)
}
fn generate_bridge(prj: &Project, build: &mut Build, rust_source_file: &Path) -> Result<()> {
let opt = Opt::default();
let generated = gen::generate_from_path(rust_source_file, &opt);
let ref rel_path = paths::local_relative_path(rust_source_file);
let cxxbridge = prj.out_dir.join("cxxbridge");
let include_dir = cxxbridge.join("include").join(&prj.include_prefix);
let sources_dir = cxxbridge.join("sources").join(&prj.include_prefix);
let ref rel_path_h = rel_path.with_appended_extension(".h");
let ref header_path = include_dir.join(rel_path_h);
out::write(header_path, &generated.header)?;
let ref link_path = include_dir.join(rel_path);
let _ = out::symlink_file(header_path, link_path);
let ref rel_path_cc = rel_path.with_appended_extension(".cc");
let ref implementation_path = sources_dir.join(rel_path_cc);
out::write(implementation_path, &generated.implementation)?;
build.file(implementation_path);
let shared_h = prj.shared_dir.join(&prj.include_prefix).join(rel_path_h);
let shared_cc = prj.shared_dir.join(&prj.include_prefix).join(rel_path_cc);
let _ = out::symlink_file(header_path, shared_h);
let _ = out::symlink_file(implementation_path, shared_cc);
Ok(())
}
fn env_os(key: impl AsRef<OsStr>) -> Result<OsString> {
let key = key.as_ref();
env::var_os(key).ok_or_else(|| Error::NoEnv(key.to_owned()))
}