forked from rust-lang/cargo
-
Notifications
You must be signed in to change notification settings - Fork 2
/
context.rs
346 lines (312 loc) · 13.1 KB
/
context.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
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
use std::collections::hash_map::{HashMap, Occupied, Vacant};
use std::str;
use std::sync::Arc;
use core::{SourceMap, Package, PackageId, PackageSet, Resolve, Target};
use util::{mod, CargoResult, ChainError, internal, Config, profile};
use util::human;
use super::{Kind, KindHost, KindTarget, Compilation, BuildConfig};
use super::TargetConfig;
use super::layout::{Layout, LayoutProxy};
use super::custom_build::BuildState;
#[deriving(Show)]
pub enum PlatformRequirement {
PlatformTarget,
PlatformPlugin,
PlatformPluginAndTarget,
}
pub struct Context<'a, 'b: 'a> {
pub config: &'b Config<'b>,
pub resolve: &'a Resolve,
pub sources: &'a SourceMap<'b>,
pub compilation: Compilation,
pub build_state: Arc<BuildState>,
env: &'a str,
host: Layout,
target: Option<Layout>,
target_triple: String,
host_dylib: Option<(String, String)>,
host_exe: String,
package_set: &'a PackageSet,
target_dylib: Option<(String, String)>,
target_exe: String,
requirements: HashMap<(&'a PackageId, &'a str), PlatformRequirement>,
build_config: BuildConfig,
}
impl<'a, 'b: 'a> Context<'a, 'b> {
pub fn new(env: &'a str, resolve: &'a Resolve, sources: &'a SourceMap<'b>,
deps: &'a PackageSet, config: &'b Config<'b>,
host: Layout, target: Option<Layout>,
root_pkg: &Package,
build_config: BuildConfig)
-> CargoResult<Context<'a, 'b>> {
let (target_dylib, target_exe) =
try!(Context::filename_parts(config.target()));
let (host_dylib, host_exe) = if config.target().is_none() {
(target_dylib.clone(),
target_exe.clone())
} else {
try!(Context::filename_parts(None))
};
let target_triple = config.target().map(|s| s.to_string());
let target_triple = target_triple.unwrap_or(config.rustc_host().to_string());
Ok(Context {
target_triple: target_triple,
env: env,
host: host,
target: target,
resolve: resolve,
sources: sources,
package_set: deps,
config: config,
target_dylib: target_dylib,
target_exe: target_exe,
host_dylib: host_dylib,
host_exe: host_exe,
requirements: HashMap::new(),
compilation: Compilation::new(root_pkg),
build_state: Arc::new(BuildState::new(build_config.clone(), deps)),
build_config: build_config,
})
}
/// Run `rustc` to discover the dylib prefix/suffix for the target
/// specified as well as the exe suffix
fn filename_parts(target: Option<&str>)
-> CargoResult<(Option<(String, String)>, String)> {
let process = util::process("rustc")
.arg("-")
.arg("--crate-name").arg("-")
.arg("--crate-type").arg("dylib")
.arg("--crate-type").arg("bin")
.arg("--print-file-name");
let process = match target {
Some(s) => process.arg("--target").arg(s),
None => process,
};
let output = try!(process.exec_with_output());
let error = str::from_utf8(output.error.as_slice()).unwrap();
let output = str::from_utf8(output.output.as_slice()).unwrap();
let mut lines = output.lines();
let dylib = if error.contains("dropping unsupported crate type `dylib`") {
None
} else {
let dylib_parts: Vec<&str> = lines.next().unwrap().trim()
.split('-').collect();
assert!(dylib_parts.len() == 2,
"rustc --print-file-name output has changed");
Some((dylib_parts[0].to_string(), dylib_parts[1].to_string()))
};
let exe_suffix = if error.contains("dropping unsupported crate type `bin`") {
String::new()
} else {
lines.next().unwrap().trim()
.split('-').skip(1).next().unwrap().to_string()
};
Ok((dylib, exe_suffix.to_string()))
}
/// Prepare this context, ensuring that all filesystem directories are in
/// place.
pub fn prepare(&mut self, pkg: &'a Package) -> CargoResult<()> {
let _p = profile::start("preparing layout");
try!(self.host.prepare().chain_error(|| {
internal(format!("couldn't prepare build directories for `{}`",
pkg.get_name()))
}));
match self.target {
Some(ref mut target) => {
try!(target.prepare().chain_error(|| {
internal(format!("couldn't prepare build directories \
for `{}`", pkg.get_name()))
}));
}
None => {}
}
let targets = pkg.get_targets().iter();
for target in targets.filter(|t| t.get_profile().is_compile()) {
self.build_requirements(pkg, target, PlatformTarget);
}
self.compilation.extra_env.insert("NUM_JOBS".to_string(),
Some(self.config.jobs().to_string()));
self.compilation.root_output =
self.layout(pkg, KindTarget).proxy().dest().clone();
self.compilation.deps_output =
self.layout(pkg, KindTarget).proxy().deps().clone();
return Ok(());
}
fn build_requirements(&mut self, pkg: &'a Package, target: &'a Target,
req: PlatformRequirement) {
let req = if target.get_profile().is_for_host() {PlatformPlugin} else {req};
match self.requirements.entry((pkg.get_package_id(), target.get_name())) {
Occupied(mut entry) => match (*entry.get(), req) {
(PlatformPlugin, PlatformPlugin) |
(PlatformPluginAndTarget, PlatformPlugin) |
(PlatformTarget, PlatformTarget) |
(PlatformPluginAndTarget, PlatformTarget) |
(PlatformPluginAndTarget, PlatformPluginAndTarget) => return,
_ => *entry.get_mut() = entry.get().combine(req),
},
Vacant(entry) => { entry.set(req); }
};
for &(pkg, dep) in self.dep_targets(pkg, target).iter() {
self.build_requirements(pkg, dep, req);
}
match pkg.get_targets().iter().find(|t| t.get_profile().is_custom_build()) {
Some(custom_build) => {
self.build_requirements(pkg, custom_build, PlatformPlugin);
}
None => {}
}
}
pub fn get_requirement(&self, pkg: &'a Package,
target: &'a Target) -> PlatformRequirement {
let default = if target.get_profile().is_for_host() {
PlatformPlugin
} else {
PlatformTarget
};
self.requirements.get(&(pkg.get_package_id(), target.get_name()))
.map(|a| *a).unwrap_or(default)
}
/// Returns the appropriate directory layout for either a plugin or not.
pub fn layout(&self, pkg: &Package, kind: Kind) -> LayoutProxy {
let primary = pkg.get_package_id() == self.resolve.root();
match kind {
KindHost => LayoutProxy::new(&self.host, primary),
KindTarget => LayoutProxy::new(self.target.as_ref()
.unwrap_or(&self.host),
primary),
}
}
/// Return the (prefix, suffix) pair for dynamic libraries.
///
/// If `plugin` is true, the pair corresponds to the host platform,
/// otherwise it corresponds to the target platform.
fn dylib(&self, kind: Kind) -> CargoResult<(&str, &str)> {
let (triple, pair) = if kind == KindHost {
(self.config.rustc_host(), &self.host_dylib)
} else {
(self.target_triple.as_slice(), &self.target_dylib)
};
match *pair {
None => return Err(human(format!("dylib outputs are not supported \
for {}", triple))),
Some((ref s1, ref s2)) => Ok((s1.as_slice(), s2.as_slice())),
}
}
/// Return the target triple which this context is targeting.
pub fn target_triple(&self) -> &str {
self.target_triple.as_slice()
}
/// Return the exact filename of the target.
pub fn target_filenames(&self, target: &Target) -> CargoResult<Vec<String>> {
let stem = target.file_stem();
let mut ret = Vec::new();
if target.is_example() || target.is_bin() ||
target.get_profile().is_test() {
ret.push(format!("{}{}", stem,
if target.get_profile().is_for_host() {
self.host_exe.as_slice()
} else {
self.target_exe.as_slice()
}));
} else {
if target.is_dylib() {
let plugin = target.get_profile().is_for_host();
let kind = if plugin {KindHost} else {KindTarget};
let (prefix, suffix) = try!(self.dylib(kind));
ret.push(format!("{}{}{}", prefix, stem, suffix));
}
if target.is_rlib() {
ret.push(format!("lib{}.rlib", stem));
}
if target.is_staticlib() {
ret.push(format!("lib{}.a", stem));
}
}
assert!(ret.len() > 0);
return Ok(ret);
}
/// For a package, return all targets which are registered as dependencies
/// for that package.
pub fn dep_targets(&self, pkg: &Package, target: &Target)
-> Vec<(&'a Package, &'a Target)> {
let deps = match self.resolve.deps(pkg.get_package_id()) {
None => return vec!(),
Some(deps) => deps,
};
deps.map(|id| self.get_package(id)).filter(|dep| {
// If this target is a build command, then we only want build
// dependencies, otherwise we want everything *other than* build
// dependencies.
let pkg_dep = pkg.get_dependencies().iter().find(|d| {
d.get_name() == dep.get_name()
}).unwrap();
target.get_profile().is_custom_build() == pkg_dep.is_build()
}).filter_map(|pkg| {
pkg.get_targets().iter().find(|&t| self.is_relevant_target(t))
.map(|t| (pkg, t))
}).collect()
}
/// Gets a package for the given package id.
pub fn get_package(&self, id: &PackageId) -> &'a Package {
self.package_set.iter()
.find(|pkg| id == pkg.get_package_id())
.expect("Should have found package")
}
pub fn env(&self) -> &str {
// The "doc-all" environment just means to document everything (see
// below), but we want to canonicalize that the the "doc" profile
// environment, so do that here.
if self.env == "doc-all" {"doc"} else {self.env}
}
pub fn is_relevant_target(&self, target: &Target) -> bool {
target.is_lib() && match self.env {
"doc" | "test" => target.get_profile().is_compile(),
// doc-all == document everything, so look for doc targets and
// compile targets in dependencies
"doc-all" => target.get_profile().is_compile() ||
(target.get_profile().get_env() == "doc" &&
target.get_profile().is_doc()),
_ => target.get_profile().get_env() == self.env &&
!target.get_profile().is_test(),
}
}
/// Get the user-specified linker for a particular host or target
pub fn linker(&self, kind: Kind) -> Option<&str> {
self.target_config(kind).linker.as_ref().map(|s| s.as_slice())
}
/// Get the user-specified `ar` program for a particular host or target
pub fn ar(&self, kind: Kind) -> Option<&str> {
self.target_config(kind).ar.as_ref().map(|s| s.as_slice())
}
/// Get the target configuration for a particular host or target
fn target_config(&self, kind: Kind) -> &TargetConfig {
match kind {
KindHost => &self.build_config.host,
KindTarget => &self.build_config.target,
}
}
}
impl PlatformRequirement {
fn combine(self, other: PlatformRequirement) -> PlatformRequirement {
match (self, other) {
(PlatformTarget, PlatformTarget) => PlatformTarget,
(PlatformPlugin, PlatformPlugin) => PlatformPlugin,
_ => PlatformPluginAndTarget,
}
}
pub fn includes(self, kind: Kind) -> bool {
match (self, kind) {
(PlatformPluginAndTarget, _) |
(PlatformTarget, KindTarget) |
(PlatformPlugin, KindHost) => true,
_ => false,
}
}
pub fn each_kind(self, f: |Kind|) {
match self {
PlatformTarget => f(KindTarget),
PlatformPlugin => f(KindHost),
PlatformPluginAndTarget => { f(KindTarget); f(KindHost); }
}
}
}