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
#![allow(
clippy::inherent_to_string,
clippy::needless_doctest_main,
clippy::new_without_default,
clippy::toplevel_ref_arg
)]
mod cargo;
mod error;
mod gen;
mod paths;
mod syntax;
use crate::error::Result;
use crate::gen::error::report;
use crate::gen::{fs, Opt};
use cc::Build;
use std::io::{self, Write};
use std::iter;
use std::path::Path;
use std::process;
#[must_use]
pub fn bridge(rust_source_file: impl AsRef<Path>) -> Build {
bridges(iter::once(rust_source_file))
}
#[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);
})
}
fn build(rust_source_files: &mut dyn Iterator<Item = impl AsRef<Path>>) -> Result<Build> {
let mut build = paths::cc_build();
build.cpp(true);
build.cpp_link_stdlib(None);
write_header()?;
for path in rust_source_files {
generate_bridge(&mut build, path.as_ref())?;
}
Ok(build)
}
fn write_header() -> Result<()> {
let ref cxx_h = paths::include_dir()?.join("rust").join("cxx.h");
let _ = write(cxx_h, gen::include::HEADER.as_bytes());
Ok(())
}
fn generate_bridge(build: &mut Build, rust_source_file: &Path) -> Result<()> {
let opt = Opt::default();
let generated = gen::generate_from_path(rust_source_file, &opt);
let header_path = paths::out_with_extension(rust_source_file, ".h")?;
fs::create_dir_all(header_path.parent().unwrap())?;
write(&header_path, &generated.header)?;
paths::symlink_header(&header_path, rust_source_file);
let implementation_path = paths::out_with_extension(rust_source_file, ".cc")?;
write(&implementation_path, &generated.implementation)?;
build.file(&implementation_path);
Ok(())
}
fn write(path: &Path, content: &[u8]) -> Result<()> {
if path.exists() {
if let Ok(existing) = fs::read(path) {
if existing == content {
return Ok(());
}
}
let _ = fs::remove_file(path);
} else {
let _ = fs::create_dir_all(path.parent().unwrap());
}
fs::write(path, content)?;
Ok(())
}