]> git.proxmox.com Git - rustc.git/blob - src/librustc_driver/driver.rs
New upstream version 1.25.0+dfsg1
[rustc.git] / src / librustc_driver / driver.rs
1 // Copyright 2012-2015 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
4 //
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
10
11 use rustc::dep_graph::DepGraph;
12 use rustc::hir::{self, map as hir_map};
13 use rustc::hir::lowering::lower_crate;
14 use rustc::ich::Fingerprint;
15 use rustc_data_structures::stable_hasher::StableHasher;
16 use rustc_mir as mir;
17 use rustc::session::{Session, CompileResult, CrateDisambiguator};
18 use rustc::session::CompileIncomplete;
19 use rustc::session::config::{self, Input, OutputFilenames, OutputType};
20 use rustc::session::search_paths::PathKind;
21 use rustc::lint;
22 use rustc::middle::{self, stability, reachable, resolve_lifetime};
23 use rustc::middle::cstore::CrateStore;
24 use rustc::middle::privacy::AccessLevels;
25 use rustc::ty::{self, TyCtxt, Resolutions, AllArenas};
26 use rustc::traits;
27 use rustc::util::common::{ErrorReported, time};
28 use rustc_allocator as allocator;
29 use rustc_borrowck as borrowck;
30 use rustc_incremental;
31 use rustc_resolve::{MakeGlobMap, Resolver, ResolverArenas};
32 use rustc_metadata::creader::CrateLoader;
33 use rustc_metadata::cstore::{self, CStore};
34 use rustc_trans_utils::trans_crate::TransCrate;
35 use rustc_typeck as typeck;
36 use rustc_privacy;
37 use rustc_plugin::registry::Registry;
38 use rustc_plugin as plugin;
39 use rustc_passes::{self, ast_validation, loops, consts, static_recursion, hir_stats};
40 use rustc_const_eval::{self, check_match};
41 use super::Compilation;
42
43 use serialize::json;
44
45 use std::any::Any;
46 use std::env;
47 use std::ffi::{OsString, OsStr};
48 use std::fs;
49 use std::io::{self, Write};
50 use std::iter;
51 use std::path::{Path, PathBuf};
52 use std::rc::Rc;
53 use std::sync::mpsc;
54 use syntax::{self, ast, attr, diagnostics, visit};
55 use syntax::ext::base::ExtCtxt;
56 use syntax::fold::Folder;
57 use syntax::parse::{self, PResult};
58 use syntax::util::node_count::NodeCounter;
59 use syntax_pos::FileName;
60 use syntax_ext;
61
62 use derive_registrar;
63 use pretty::ReplaceBodyWithLoop;
64
65 use profile;
66
67 pub fn compile_input(trans: Box<TransCrate>,
68 sess: &Session,
69 cstore: &CStore,
70 input_path: &Option<PathBuf>,
71 input: &Input,
72 outdir: &Option<PathBuf>,
73 output: &Option<PathBuf>,
74 addl_plugins: Option<Vec<String>>,
75 control: &CompileController) -> CompileResult {
76 macro_rules! controller_entry_point {
77 ($point: ident, $tsess: expr, $make_state: expr, $phase_result: expr) => {{
78 let state = &mut $make_state;
79 let phase_result: &CompileResult = &$phase_result;
80 if phase_result.is_ok() || control.$point.run_callback_on_error {
81 (control.$point.callback)(state);
82 }
83
84 if control.$point.stop == Compilation::Stop {
85 // FIXME: shouldn't this return Err(CompileIncomplete::Stopped)
86 // if there are no errors?
87 return $tsess.compile_status();
88 }
89 }}
90 }
91
92 if sess.profile_queries() {
93 profile::begin();
94 }
95
96 // We need nested scopes here, because the intermediate results can keep
97 // large chunks of memory alive and we want to free them as soon as
98 // possible to keep the peak memory usage low
99 let (outputs, ongoing_trans, dep_graph) = {
100 let krate = match phase_1_parse_input(control, sess, input) {
101 Ok(krate) => krate,
102 Err(mut parse_error) => {
103 parse_error.emit();
104 return Err(CompileIncomplete::Errored(ErrorReported));
105 }
106 };
107
108 let (krate, registry) = {
109 let mut compile_state = CompileState::state_after_parse(input,
110 sess,
111 outdir,
112 output,
113 krate,
114 &cstore);
115 controller_entry_point!(after_parse,
116 sess,
117 compile_state,
118 Ok(()));
119
120 (compile_state.krate.unwrap(), compile_state.registry)
121 };
122
123 let outputs = build_output_filenames(input, outdir, output, &krate.attrs, sess);
124 let crate_name =
125 ::rustc_trans_utils::link::find_crate_name(Some(sess), &krate.attrs, input);
126 let ExpansionResult { expanded_crate, defs, analysis, resolutions, mut hir_forest } = {
127 phase_2_configure_and_expand(
128 sess,
129 &cstore,
130 krate,
131 registry,
132 &crate_name,
133 addl_plugins,
134 control.make_glob_map,
135 |expanded_crate| {
136 let mut state = CompileState::state_after_expand(
137 input, sess, outdir, output, &cstore, expanded_crate, &crate_name,
138 );
139 controller_entry_point!(after_expand, sess, state, Ok(()));
140 Ok(())
141 }
142 )?
143 };
144
145 let output_paths = generated_output_paths(sess, &outputs, output.is_some(), &crate_name);
146
147 // Ensure the source file isn't accidentally overwritten during compilation.
148 if let Some(ref input_path) = *input_path {
149 if sess.opts.will_create_output_file() {
150 if output_contains_path(&output_paths, input_path) {
151 sess.err(&format!(
152 "the input file \"{}\" would be overwritten by the generated \
153 executable",
154 input_path.display()));
155 return Err(CompileIncomplete::Stopped);
156 }
157 if let Some(dir_path) = output_conflicts_with_dir(&output_paths) {
158 sess.err(&format!(
159 "the generated executable for the input file \"{}\" conflicts with the \
160 existing directory \"{}\"",
161 input_path.display(), dir_path.display()));
162 return Err(CompileIncomplete::Stopped);
163 }
164 }
165 }
166
167 write_out_deps(sess, &outputs, &output_paths);
168 if sess.opts.output_types.contains_key(&OutputType::DepInfo) &&
169 sess.opts.output_types.keys().count() == 1 {
170 return Ok(())
171 }
172
173 if let &Some(ref dir) = outdir {
174 if fs::create_dir_all(dir).is_err() {
175 sess.err("failed to find or create the directory specified by --out-dir");
176 return Err(CompileIncomplete::Stopped);
177 }
178 }
179
180 let arenas = AllArenas::new();
181
182 // Construct the HIR map
183 let hir_map = time(sess.time_passes(),
184 "indexing hir",
185 || hir_map::map_crate(sess, cstore, &mut hir_forest, &defs));
186
187 {
188 hir_map.dep_graph.assert_ignored();
189 controller_entry_point!(after_hir_lowering,
190 sess,
191 CompileState::state_after_hir_lowering(input,
192 sess,
193 outdir,
194 output,
195 &arenas,
196 &cstore,
197 &hir_map,
198 &analysis,
199 &resolutions,
200 &expanded_crate,
201 &hir_map.krate(),
202 &outputs,
203 &crate_name),
204 Ok(()));
205 }
206
207 let opt_crate = if control.keep_ast {
208 Some(&expanded_crate)
209 } else {
210 drop(expanded_crate);
211 None
212 };
213
214 phase_3_run_analysis_passes(&*trans,
215 control,
216 sess,
217 cstore,
218 hir_map,
219 analysis,
220 resolutions,
221 &arenas,
222 &crate_name,
223 &outputs,
224 |tcx, analysis, rx, result| {
225 {
226 // Eventually, we will want to track plugins.
227 tcx.dep_graph.with_ignore(|| {
228 let mut state = CompileState::state_after_analysis(input,
229 sess,
230 outdir,
231 output,
232 opt_crate,
233 tcx.hir.krate(),
234 &analysis,
235 tcx,
236 &crate_name);
237 (control.after_analysis.callback)(&mut state);
238 });
239
240 if control.after_analysis.stop == Compilation::Stop {
241 return result.and_then(|_| Err(CompileIncomplete::Stopped));
242 }
243 }
244
245 result?;
246
247 if log_enabled!(::log::Level::Info) {
248 println!("Pre-trans");
249 tcx.print_debug_stats();
250 }
251
252 let ongoing_trans = phase_4_translate_to_llvm(&*trans, tcx, rx);
253
254 if log_enabled!(::log::Level::Info) {
255 println!("Post-trans");
256 tcx.print_debug_stats();
257 }
258
259 if tcx.sess.opts.output_types.contains_key(&OutputType::Mir) {
260 if let Err(e) = mir::transform::dump_mir::emit_mir(tcx, &outputs) {
261 sess.err(&format!("could not emit MIR: {}", e));
262 sess.abort_if_errors();
263 }
264 }
265
266 Ok((outputs.clone(), ongoing_trans, tcx.dep_graph.clone()))
267 })??
268 };
269
270 if sess.opts.debugging_opts.print_type_sizes {
271 sess.code_stats.borrow().print_type_sizes();
272 }
273
274 trans.join_trans_and_link(ongoing_trans, sess, &dep_graph, &outputs)?;
275
276 if sess.opts.debugging_opts.perf_stats {
277 sess.print_perf_stats();
278 }
279
280 controller_entry_point!(
281 compilation_done,
282 sess,
283 CompileState::state_when_compilation_done(input, sess, outdir, output),
284 Ok(())
285 );
286
287 Ok(())
288 }
289
290 pub fn source_name(input: &Input) -> FileName {
291 match *input {
292 Input::File(ref ifile) => ifile.clone().into(),
293 Input::Str { ref name, .. } => name.clone(),
294 }
295 }
296
297 /// CompileController is used to customize compilation, it allows compilation to
298 /// be stopped and/or to call arbitrary code at various points in compilation.
299 /// It also allows for various flags to be set to influence what information gets
300 /// collected during compilation.
301 ///
302 /// This is a somewhat higher level controller than a Session - the Session
303 /// controls what happens in each phase, whereas the CompileController controls
304 /// whether a phase is run at all and whether other code (from outside the
305 /// compiler) is run between phases.
306 ///
307 /// Note that if compilation is set to stop and a callback is provided for a
308 /// given entry point, the callback is called before compilation is stopped.
309 ///
310 /// Expect more entry points to be added in the future.
311 pub struct CompileController<'a> {
312 pub after_parse: PhaseController<'a>,
313 pub after_expand: PhaseController<'a>,
314 pub after_hir_lowering: PhaseController<'a>,
315 pub after_analysis: PhaseController<'a>,
316 pub compilation_done: PhaseController<'a>,
317
318 // FIXME we probably want to group the below options together and offer a
319 // better API, rather than this ad-hoc approach.
320 pub make_glob_map: MakeGlobMap,
321 // Whether the compiler should keep the ast beyond parsing.
322 pub keep_ast: bool,
323 // -Zcontinue-parse-after-error
324 pub continue_parse_after_error: bool,
325
326 /// Allows overriding default rustc query providers,
327 /// after `default_provide` has installed them.
328 pub provide: Box<Fn(&mut ty::maps::Providers) + 'a>,
329 /// Same as `provide`, but only for non-local crates,
330 /// applied after `default_provide_extern`.
331 pub provide_extern: Box<Fn(&mut ty::maps::Providers) + 'a>,
332 }
333
334 impl<'a> CompileController<'a> {
335 pub fn basic() -> CompileController<'a> {
336 CompileController {
337 after_parse: PhaseController::basic(),
338 after_expand: PhaseController::basic(),
339 after_hir_lowering: PhaseController::basic(),
340 after_analysis: PhaseController::basic(),
341 compilation_done: PhaseController::basic(),
342 make_glob_map: MakeGlobMap::No,
343 keep_ast: false,
344 continue_parse_after_error: false,
345 provide: box |_| {},
346 provide_extern: box |_| {},
347 }
348 }
349 }
350
351 pub struct PhaseController<'a> {
352 pub stop: Compilation,
353 // If true then the compiler will try to run the callback even if the phase
354 // ends with an error. Note that this is not always possible.
355 pub run_callback_on_error: bool,
356 pub callback: Box<Fn(&mut CompileState) + 'a>,
357 }
358
359 impl<'a> PhaseController<'a> {
360 pub fn basic() -> PhaseController<'a> {
361 PhaseController {
362 stop: Compilation::Continue,
363 run_callback_on_error: false,
364 callback: box |_| {},
365 }
366 }
367 }
368
369 /// State that is passed to a callback. What state is available depends on when
370 /// during compilation the callback is made. See the various constructor methods
371 /// (`state_*`) in the impl to see which data is provided for any given entry point.
372 pub struct CompileState<'a, 'tcx: 'a> {
373 pub input: &'a Input,
374 pub session: &'tcx Session,
375 pub krate: Option<ast::Crate>,
376 pub registry: Option<Registry<'a>>,
377 pub cstore: Option<&'tcx CStore>,
378 pub crate_name: Option<&'a str>,
379 pub output_filenames: Option<&'a OutputFilenames>,
380 pub out_dir: Option<&'a Path>,
381 pub out_file: Option<&'a Path>,
382 pub arenas: Option<&'tcx AllArenas<'tcx>>,
383 pub expanded_crate: Option<&'a ast::Crate>,
384 pub hir_crate: Option<&'a hir::Crate>,
385 pub hir_map: Option<&'a hir_map::Map<'tcx>>,
386 pub resolutions: Option<&'a Resolutions>,
387 pub analysis: Option<&'a ty::CrateAnalysis>,
388 pub tcx: Option<TyCtxt<'a, 'tcx, 'tcx>>,
389 }
390
391 impl<'a, 'tcx> CompileState<'a, 'tcx> {
392 fn empty(input: &'a Input,
393 session: &'tcx Session,
394 out_dir: &'a Option<PathBuf>)
395 -> Self {
396 CompileState {
397 input,
398 session,
399 out_dir: out_dir.as_ref().map(|s| &**s),
400 out_file: None,
401 arenas: None,
402 krate: None,
403 registry: None,
404 cstore: None,
405 crate_name: None,
406 output_filenames: None,
407 expanded_crate: None,
408 hir_crate: None,
409 hir_map: None,
410 resolutions: None,
411 analysis: None,
412 tcx: None,
413 }
414 }
415
416 fn state_after_parse(input: &'a Input,
417 session: &'tcx Session,
418 out_dir: &'a Option<PathBuf>,
419 out_file: &'a Option<PathBuf>,
420 krate: ast::Crate,
421 cstore: &'tcx CStore)
422 -> Self {
423 CompileState {
424 // Initialize the registry before moving `krate`
425 registry: Some(Registry::new(&session, krate.span)),
426 krate: Some(krate),
427 cstore: Some(cstore),
428 out_file: out_file.as_ref().map(|s| &**s),
429 ..CompileState::empty(input, session, out_dir)
430 }
431 }
432
433 fn state_after_expand(input: &'a Input,
434 session: &'tcx Session,
435 out_dir: &'a Option<PathBuf>,
436 out_file: &'a Option<PathBuf>,
437 cstore: &'tcx CStore,
438 expanded_crate: &'a ast::Crate,
439 crate_name: &'a str)
440 -> Self {
441 CompileState {
442 crate_name: Some(crate_name),
443 cstore: Some(cstore),
444 expanded_crate: Some(expanded_crate),
445 out_file: out_file.as_ref().map(|s| &**s),
446 ..CompileState::empty(input, session, out_dir)
447 }
448 }
449
450 fn state_after_hir_lowering(input: &'a Input,
451 session: &'tcx Session,
452 out_dir: &'a Option<PathBuf>,
453 out_file: &'a Option<PathBuf>,
454 arenas: &'tcx AllArenas<'tcx>,
455 cstore: &'tcx CStore,
456 hir_map: &'a hir_map::Map<'tcx>,
457 analysis: &'a ty::CrateAnalysis,
458 resolutions: &'a Resolutions,
459 krate: &'a ast::Crate,
460 hir_crate: &'a hir::Crate,
461 output_filenames: &'a OutputFilenames,
462 crate_name: &'a str)
463 -> Self {
464 CompileState {
465 crate_name: Some(crate_name),
466 arenas: Some(arenas),
467 cstore: Some(cstore),
468 hir_map: Some(hir_map),
469 analysis: Some(analysis),
470 resolutions: Some(resolutions),
471 expanded_crate: Some(krate),
472 hir_crate: Some(hir_crate),
473 output_filenames: Some(output_filenames),
474 out_file: out_file.as_ref().map(|s| &**s),
475 ..CompileState::empty(input, session, out_dir)
476 }
477 }
478
479 fn state_after_analysis(input: &'a Input,
480 session: &'tcx Session,
481 out_dir: &'a Option<PathBuf>,
482 out_file: &'a Option<PathBuf>,
483 krate: Option<&'a ast::Crate>,
484 hir_crate: &'a hir::Crate,
485 analysis: &'a ty::CrateAnalysis,
486 tcx: TyCtxt<'a, 'tcx, 'tcx>,
487 crate_name: &'a str)
488 -> Self {
489 CompileState {
490 analysis: Some(analysis),
491 tcx: Some(tcx),
492 expanded_crate: krate,
493 hir_crate: Some(hir_crate),
494 crate_name: Some(crate_name),
495 out_file: out_file.as_ref().map(|s| &**s),
496 ..CompileState::empty(input, session, out_dir)
497 }
498 }
499
500 fn state_when_compilation_done(input: &'a Input,
501 session: &'tcx Session,
502 out_dir: &'a Option<PathBuf>,
503 out_file: &'a Option<PathBuf>)
504 -> Self {
505 CompileState {
506 out_file: out_file.as_ref().map(|s| &**s),
507 ..CompileState::empty(input, session, out_dir)
508 }
509 }
510 }
511
512 pub fn phase_1_parse_input<'a>(control: &CompileController,
513 sess: &'a Session,
514 input: &Input)
515 -> PResult<'a, ast::Crate> {
516 sess.diagnostic().set_continue_after_error(control.continue_parse_after_error);
517
518 if sess.profile_queries() {
519 profile::begin();
520 }
521
522 let krate = time(sess.time_passes(), "parsing", || {
523 match *input {
524 Input::File(ref file) => {
525 parse::parse_crate_from_file(file, &sess.parse_sess)
526 }
527 Input::Str { ref input, ref name } => {
528 parse::parse_crate_from_source_str(name.clone(),
529 input.clone(),
530 &sess.parse_sess)
531 }
532 }
533 })?;
534
535 sess.diagnostic().set_continue_after_error(true);
536
537 if sess.opts.debugging_opts.ast_json_noexpand {
538 println!("{}", json::as_json(&krate));
539 }
540
541 if sess.opts.debugging_opts.input_stats {
542 println!("Lines of code: {}", sess.codemap().count_lines());
543 println!("Pre-expansion node count: {}", count_nodes(&krate));
544 }
545
546 if let Some(ref s) = sess.opts.debugging_opts.show_span {
547 syntax::show_span::run(sess.diagnostic(), s, &krate);
548 }
549
550 if sess.opts.debugging_opts.hir_stats {
551 hir_stats::print_ast_stats(&krate, "PRE EXPANSION AST STATS");
552 }
553
554 Ok(krate)
555 }
556
557 fn count_nodes(krate: &ast::Crate) -> usize {
558 let mut counter = NodeCounter::new();
559 visit::walk_crate(&mut counter, krate);
560 counter.count
561 }
562
563 // For continuing compilation after a parsed crate has been
564 // modified
565
566 pub struct ExpansionResult {
567 pub expanded_crate: ast::Crate,
568 pub defs: hir_map::Definitions,
569 pub analysis: ty::CrateAnalysis,
570 pub resolutions: Resolutions,
571 pub hir_forest: hir_map::Forest,
572 }
573
574 pub struct InnerExpansionResult<'a> {
575 pub expanded_crate: ast::Crate,
576 pub resolver: Resolver<'a>,
577 pub hir_forest: hir_map::Forest,
578 }
579
580 /// Run the "early phases" of the compiler: initial `cfg` processing,
581 /// loading compiler plugins (including those from `addl_plugins`),
582 /// syntax expansion, secondary `cfg` expansion, synthesis of a test
583 /// harness if one is to be provided, injection of a dependency on the
584 /// standard library and prelude, and name resolution.
585 ///
586 /// Returns `None` if we're aborting after handling -W help.
587 pub fn phase_2_configure_and_expand<F>(sess: &Session,
588 cstore: &CStore,
589 krate: ast::Crate,
590 registry: Option<Registry>,
591 crate_name: &str,
592 addl_plugins: Option<Vec<String>>,
593 make_glob_map: MakeGlobMap,
594 after_expand: F)
595 -> Result<ExpansionResult, CompileIncomplete>
596 where F: FnOnce(&ast::Crate) -> CompileResult {
597 // Currently, we ignore the name resolution data structures for the purposes of dependency
598 // tracking. Instead we will run name resolution and include its output in the hash of each
599 // item, much like we do for macro expansion. In other words, the hash reflects not just
600 // its contents but the results of name resolution on those contents. Hopefully we'll push
601 // this back at some point.
602 let mut crate_loader = CrateLoader::new(sess, &cstore, &crate_name);
603 let resolver_arenas = Resolver::arenas();
604 let result = phase_2_configure_and_expand_inner(sess, cstore, krate, registry, crate_name,
605 addl_plugins, make_glob_map, &resolver_arenas,
606 &mut crate_loader, after_expand);
607 match result {
608 Ok(InnerExpansionResult {expanded_crate, resolver, hir_forest}) => {
609 Ok(ExpansionResult {
610 expanded_crate,
611 defs: resolver.definitions,
612 hir_forest,
613 resolutions: Resolutions {
614 freevars: resolver.freevars,
615 export_map: resolver.export_map,
616 trait_map: resolver.trait_map,
617 maybe_unused_trait_imports: resolver.maybe_unused_trait_imports,
618 maybe_unused_extern_crates: resolver.maybe_unused_extern_crates,
619 },
620
621 analysis: ty::CrateAnalysis {
622 access_levels: Rc::new(AccessLevels::default()),
623 name: crate_name.to_string(),
624 glob_map: if resolver.make_glob_map { Some(resolver.glob_map) } else { None },
625 },
626 })
627 }
628 Err(x) => Err(x)
629 }
630 }
631
632 /// Same as phase_2_configure_and_expand, but doesn't let you keep the resolver
633 /// around
634 pub fn phase_2_configure_and_expand_inner<'a, F>(sess: &'a Session,
635 cstore: &'a CStore,
636 krate: ast::Crate,
637 registry: Option<Registry>,
638 crate_name: &str,
639 addl_plugins: Option<Vec<String>>,
640 make_glob_map: MakeGlobMap,
641 resolver_arenas: &'a ResolverArenas<'a>,
642 crate_loader: &'a mut CrateLoader,
643 after_expand: F)
644 -> Result<InnerExpansionResult<'a>, CompileIncomplete>
645 where F: FnOnce(&ast::Crate) -> CompileResult,
646 {
647 let time_passes = sess.time_passes();
648
649 let (mut krate, features) = syntax::config::features(krate, &sess.parse_sess, sess.opts.test);
650 // these need to be set "early" so that expansion sees `quote` if enabled.
651 *sess.features.borrow_mut() = features;
652
653 *sess.crate_types.borrow_mut() = collect_crate_types(sess, &krate.attrs);
654
655 let disambiguator = compute_crate_disambiguator(sess);
656 *sess.crate_disambiguator.borrow_mut() = Some(disambiguator);
657 rustc_incremental::prepare_session_directory(
658 sess,
659 &crate_name,
660 disambiguator,
661 );
662
663 if sess.opts.incremental.is_some() {
664 time(time_passes, "garbage collect incremental cache directory", || {
665 if let Err(e) = rustc_incremental::garbage_collect_session_directories(sess) {
666 warn!("Error while trying to garbage collect incremental \
667 compilation cache directory: {}", e);
668 }
669 });
670 }
671
672 // If necessary, compute the dependency graph (in the background).
673 let future_dep_graph = if sess.opts.build_dep_graph() {
674 Some(rustc_incremental::load_dep_graph(sess, time_passes))
675 } else {
676 None
677 };
678
679 time(time_passes, "recursion limit", || {
680 middle::recursion_limit::update_limits(sess, &krate);
681 });
682
683 krate = time(time_passes, "crate injection", || {
684 let alt_std_name = sess.opts.alt_std_name.clone();
685 syntax::std_inject::maybe_inject_crates_ref(krate, alt_std_name)
686 });
687
688 let mut addl_plugins = Some(addl_plugins);
689 let registrars = time(time_passes, "plugin loading", || {
690 plugin::load::load_plugins(sess,
691 &cstore,
692 &krate,
693 crate_name,
694 addl_plugins.take().unwrap())
695 });
696
697 let mut registry = registry.unwrap_or(Registry::new(sess, krate.span));
698
699 time(time_passes, "plugin registration", || {
700 if sess.features.borrow().rustc_diagnostic_macros {
701 registry.register_macro("__diagnostic_used",
702 diagnostics::plugin::expand_diagnostic_used);
703 registry.register_macro("__register_diagnostic",
704 diagnostics::plugin::expand_register_diagnostic);
705 registry.register_macro("__build_diagnostic_array",
706 diagnostics::plugin::expand_build_diagnostic_array);
707 }
708
709 for registrar in registrars {
710 registry.args_hidden = Some(registrar.args);
711 (registrar.fun)(&mut registry);
712 }
713 });
714
715 let whitelisted_legacy_custom_derives = registry.take_whitelisted_custom_derives();
716 let Registry { syntax_exts, early_lint_passes, late_lint_passes, lint_groups,
717 llvm_passes, attributes, .. } = registry;
718
719 sess.track_errors(|| {
720 let mut ls = sess.lint_store.borrow_mut();
721 for pass in early_lint_passes {
722 ls.register_early_pass(Some(sess), true, pass);
723 }
724 for pass in late_lint_passes {
725 ls.register_late_pass(Some(sess), true, pass);
726 }
727
728 for (name, to) in lint_groups {
729 ls.register_group(Some(sess), true, name, to);
730 }
731
732 *sess.plugin_llvm_passes.borrow_mut() = llvm_passes;
733 *sess.plugin_attributes.borrow_mut() = attributes.clone();
734 })?;
735
736 // Lint plugins are registered; now we can process command line flags.
737 if sess.opts.describe_lints {
738 super::describe_lints(&sess.lint_store.borrow(), true);
739 return Err(CompileIncomplete::Stopped);
740 }
741
742 let mut resolver = Resolver::new(sess,
743 cstore,
744 &krate,
745 crate_name,
746 make_glob_map,
747 crate_loader,
748 &resolver_arenas);
749 resolver.whitelisted_legacy_custom_derives = whitelisted_legacy_custom_derives;
750 syntax_ext::register_builtins(&mut resolver, syntax_exts, sess.features.borrow().quote);
751
752 krate = time(time_passes, "expansion", || {
753 // Windows dlls do not have rpaths, so they don't know how to find their
754 // dependencies. It's up to us to tell the system where to find all the
755 // dependent dlls. Note that this uses cfg!(windows) as opposed to
756 // targ_cfg because syntax extensions are always loaded for the host
757 // compiler, not for the target.
758 //
759 // This is somewhat of an inherently racy operation, however, as
760 // multiple threads calling this function could possibly continue
761 // extending PATH far beyond what it should. To solve this for now we
762 // just don't add any new elements to PATH which are already there
763 // within PATH. This is basically a targeted fix at #17360 for rustdoc
764 // which runs rustc in parallel but has been seen (#33844) to cause
765 // problems with PATH becoming too long.
766 let mut old_path = OsString::new();
767 if cfg!(windows) {
768 old_path = env::var_os("PATH").unwrap_or(old_path);
769 let mut new_path = sess.host_filesearch(PathKind::All)
770 .get_dylib_search_paths();
771 for path in env::split_paths(&old_path) {
772 if !new_path.contains(&path) {
773 new_path.push(path);
774 }
775 }
776 env::set_var("PATH",
777 &env::join_paths(new_path.iter()
778 .filter(|p| env::join_paths(iter::once(p)).is_ok()))
779 .unwrap());
780 }
781 let features = sess.features.borrow();
782 let cfg = syntax::ext::expand::ExpansionConfig {
783 features: Some(&features),
784 recursion_limit: sess.recursion_limit.get(),
785 trace_mac: sess.opts.debugging_opts.trace_macros,
786 should_test: sess.opts.test,
787 ..syntax::ext::expand::ExpansionConfig::default(crate_name.to_string())
788 };
789
790 let mut ecx = ExtCtxt::new(&sess.parse_sess, cfg, &mut resolver);
791 let err_count = ecx.parse_sess.span_diagnostic.err_count();
792
793 let krate = ecx.monotonic_expander().expand_crate(krate);
794
795 ecx.check_unused_macros();
796
797 let mut missing_fragment_specifiers: Vec<_> =
798 ecx.parse_sess.missing_fragment_specifiers.borrow().iter().cloned().collect();
799 missing_fragment_specifiers.sort();
800 for span in missing_fragment_specifiers {
801 let lint = lint::builtin::MISSING_FRAGMENT_SPECIFIER;
802 let msg = "missing fragment specifier";
803 sess.buffer_lint(lint, ast::CRATE_NODE_ID, span, msg);
804 }
805 if ecx.parse_sess.span_diagnostic.err_count() - ecx.resolve_err_count > err_count {
806 ecx.parse_sess.span_diagnostic.abort_if_errors();
807 }
808 if cfg!(windows) {
809 env::set_var("PATH", &old_path);
810 }
811 krate
812 });
813
814 krate = time(time_passes, "maybe building test harness", || {
815 syntax::test::modify_for_testing(&sess.parse_sess,
816 &mut resolver,
817 sess.opts.test,
818 krate,
819 sess.diagnostic())
820 });
821
822 // If we're actually rustdoc then there's no need to actually compile
823 // anything, so switch everything to just looping
824 if sess.opts.actually_rustdoc {
825 krate = ReplaceBodyWithLoop::new(sess).fold_crate(krate);
826 }
827
828 // If we're in rustdoc we're always compiling as an rlib, but that'll trip a
829 // bunch of checks in the `modify` function below. For now just skip this
830 // step entirely if we're rustdoc as it's not too useful anyway.
831 if !sess.opts.actually_rustdoc {
832 krate = time(time_passes, "maybe creating a macro crate", || {
833 let crate_types = sess.crate_types.borrow();
834 let num_crate_types = crate_types.len();
835 let is_proc_macro_crate = crate_types.contains(&config::CrateTypeProcMacro);
836 let is_test_crate = sess.opts.test;
837 syntax_ext::proc_macro_registrar::modify(&sess.parse_sess,
838 &mut resolver,
839 krate,
840 is_proc_macro_crate,
841 is_test_crate,
842 num_crate_types,
843 sess.diagnostic())
844 });
845 }
846
847 krate = time(time_passes, "creating allocators", || {
848 allocator::expand::modify(&sess.parse_sess,
849 &mut resolver,
850 krate,
851 sess.diagnostic())
852 });
853
854 after_expand(&krate)?;
855
856 if sess.opts.debugging_opts.input_stats {
857 println!("Post-expansion node count: {}", count_nodes(&krate));
858 }
859
860 if sess.opts.debugging_opts.hir_stats {
861 hir_stats::print_ast_stats(&krate, "POST EXPANSION AST STATS");
862 }
863
864 if sess.opts.debugging_opts.ast_json {
865 println!("{}", json::as_json(&krate));
866 }
867
868 time(time_passes,
869 "AST validation",
870 || ast_validation::check_crate(sess, &krate));
871
872 time(time_passes, "name resolution", || -> CompileResult {
873 resolver.resolve_crate(&krate);
874 Ok(())
875 })?;
876
877 if resolver.found_unresolved_macro {
878 sess.parse_sess.span_diagnostic.abort_if_errors();
879 }
880
881 // Needs to go *after* expansion to be able to check the results of macro expansion.
882 time(time_passes, "complete gated feature checking", || {
883 sess.track_errors(|| {
884 syntax::feature_gate::check_crate(&krate,
885 &sess.parse_sess,
886 &sess.features.borrow(),
887 &attributes,
888 sess.opts.unstable_features);
889 })
890 })?;
891
892 // Lower ast -> hir.
893 // First, we need to collect the dep_graph.
894 let dep_graph = match future_dep_graph {
895 None => DepGraph::new_disabled(),
896 Some(future) => {
897 let prev_graph = time(time_passes, "blocked while dep-graph loading finishes", || {
898 future.open()
899 .expect("Could not join with background dep_graph thread")
900 .open(sess)
901 });
902 DepGraph::new(prev_graph)
903 }
904 };
905 let hir_forest = time(time_passes, "lowering ast -> hir", || {
906 let hir_crate = lower_crate(sess, cstore, &dep_graph, &krate, &mut resolver);
907
908 if sess.opts.debugging_opts.hir_stats {
909 hir_stats::print_hir_stats(&hir_crate);
910 }
911
912 hir_map::Forest::new(hir_crate, &dep_graph)
913 });
914
915 time(time_passes,
916 "early lint checks",
917 || lint::check_ast_crate(sess, &krate));
918
919 // Discard hygiene data, which isn't required after lowering to HIR.
920 if !sess.opts.debugging_opts.keep_hygiene_data {
921 syntax::ext::hygiene::clear_markings();
922 }
923
924 Ok(InnerExpansionResult {
925 expanded_crate: krate,
926 resolver,
927 hir_forest,
928 })
929 }
930
931 pub fn default_provide(providers: &mut ty::maps::Providers) {
932 borrowck::provide(providers);
933 mir::provide(providers);
934 reachable::provide(providers);
935 resolve_lifetime::provide(providers);
936 rustc_privacy::provide(providers);
937 typeck::provide(providers);
938 ty::provide(providers);
939 traits::provide(providers);
940 reachable::provide(providers);
941 rustc_const_eval::provide(providers);
942 rustc_passes::provide(providers);
943 middle::region::provide(providers);
944 cstore::provide(providers);
945 lint::provide(providers);
946 }
947
948 pub fn default_provide_extern(providers: &mut ty::maps::Providers) {
949 cstore::provide_extern(providers);
950 }
951
952 /// Run the resolution, typechecking, region checking and other
953 /// miscellaneous analysis passes on the crate. Return various
954 /// structures carrying the results of the analysis.
955 pub fn phase_3_run_analysis_passes<'tcx, F, R>(trans: &TransCrate,
956 control: &CompileController,
957 sess: &'tcx Session,
958 cstore: &'tcx CrateStore,
959 hir_map: hir_map::Map<'tcx>,
960 mut analysis: ty::CrateAnalysis,
961 resolutions: Resolutions,
962 arenas: &'tcx AllArenas<'tcx>,
963 name: &str,
964 output_filenames: &OutputFilenames,
965 f: F)
966 -> Result<R, CompileIncomplete>
967 where F: for<'a> FnOnce(TyCtxt<'a, 'tcx, 'tcx>,
968 ty::CrateAnalysis,
969 mpsc::Receiver<Box<Any + Send>>,
970 CompileResult) -> R
971 {
972 let time_passes = sess.time_passes();
973
974 let query_result_on_disk_cache = time(time_passes,
975 "load query result cache",
976 || rustc_incremental::load_query_result_cache(sess));
977
978 time(time_passes,
979 "looking for entry point",
980 || middle::entry::find_entry_point(sess, &hir_map));
981
982 sess.plugin_registrar_fn.set(time(time_passes, "looking for plugin registrar", || {
983 plugin::build::find_plugin_registrar(sess.diagnostic(), &hir_map)
984 }));
985 sess.derive_registrar_fn.set(derive_registrar::find(&hir_map));
986
987 time(time_passes,
988 "loop checking",
989 || loops::check_crate(sess, &hir_map));
990
991 time(time_passes,
992 "static item recursion checking",
993 || static_recursion::check_crate(sess, &hir_map))?;
994
995 let mut local_providers = ty::maps::Providers::default();
996 default_provide(&mut local_providers);
997 trans.provide(&mut local_providers);
998 (control.provide)(&mut local_providers);
999
1000 let mut extern_providers = local_providers;
1001 default_provide_extern(&mut extern_providers);
1002 trans.provide_extern(&mut extern_providers);
1003 (control.provide_extern)(&mut extern_providers);
1004
1005 let (tx, rx) = mpsc::channel();
1006
1007 TyCtxt::create_and_enter(sess,
1008 cstore,
1009 local_providers,
1010 extern_providers,
1011 arenas,
1012 resolutions,
1013 hir_map,
1014 query_result_on_disk_cache,
1015 name,
1016 tx,
1017 output_filenames,
1018 |tcx| {
1019 // Do some initialization of the DepGraph that can only be done with the
1020 // tcx available.
1021 rustc_incremental::dep_graph_tcx_init(tcx);
1022
1023 time(sess.time_passes(), "attribute checking", || {
1024 hir::check_attr::check_crate(tcx)
1025 });
1026
1027 time(time_passes,
1028 "stability checking",
1029 || stability::check_unstable_api_usage(tcx));
1030
1031 // passes are timed inside typeck
1032 match typeck::check_crate(tcx) {
1033 Ok(x) => x,
1034 Err(x) => {
1035 f(tcx, analysis, rx, Err(x));
1036 return Err(x);
1037 }
1038 }
1039
1040 time(time_passes,
1041 "const checking",
1042 || consts::check_crate(tcx));
1043
1044 analysis.access_levels =
1045 time(time_passes, "privacy checking", || rustc_privacy::check_crate(tcx));
1046
1047 time(time_passes,
1048 "intrinsic checking",
1049 || middle::intrinsicck::check_crate(tcx));
1050
1051 time(time_passes,
1052 "match checking",
1053 || check_match::check_crate(tcx));
1054
1055 // this must run before MIR dump, because
1056 // "not all control paths return a value" is reported here.
1057 //
1058 // maybe move the check to a MIR pass?
1059 time(time_passes,
1060 "liveness checking",
1061 || middle::liveness::check_crate(tcx));
1062
1063 time(time_passes,
1064 "borrow checking",
1065 || borrowck::check_crate(tcx));
1066
1067 time(time_passes,
1068 "MIR borrow checking",
1069 || for def_id in tcx.body_owners() { tcx.mir_borrowck(def_id); });
1070
1071 time(time_passes,
1072 "MIR effect checking",
1073 || for def_id in tcx.body_owners() {
1074 mir::transform::check_unsafety::check_unsafety(tcx, def_id)
1075 });
1076 // Avoid overwhelming user with errors if type checking failed.
1077 // I'm not sure how helpful this is, to be honest, but it avoids
1078 // a
1079 // lot of annoying errors in the compile-fail tests (basically,
1080 // lint warnings and so on -- kindck used to do this abort, but
1081 // kindck is gone now). -nmatsakis
1082 if sess.err_count() > 0 {
1083 return Ok(f(tcx, analysis, rx, sess.compile_status()));
1084 }
1085
1086 time(time_passes, "death checking", || middle::dead::check_crate(tcx));
1087
1088 time(time_passes, "unused lib feature checking", || {
1089 stability::check_unused_or_stable_features(tcx)
1090 });
1091
1092 time(time_passes, "lint checking", || lint::check_crate(tcx));
1093
1094 return Ok(f(tcx, analysis, rx, tcx.sess.compile_status()));
1095 })
1096 }
1097
1098 /// Run the translation phase to LLVM, after which the AST and analysis can
1099 /// be discarded.
1100 pub fn phase_4_translate_to_llvm<'a, 'tcx>(trans: &TransCrate,
1101 tcx: TyCtxt<'a, 'tcx, 'tcx>,
1102 rx: mpsc::Receiver<Box<Any + Send>>)
1103 -> Box<Any> {
1104 let time_passes = tcx.sess.time_passes();
1105
1106 time(time_passes,
1107 "resolving dependency formats",
1108 || ::rustc::middle::dependency_format::calculate(tcx));
1109
1110 let translation =
1111 time(time_passes, "translation", move || {
1112 trans.trans_crate(tcx, rx)
1113 });
1114 if tcx.sess.profile_queries() {
1115 profile::dump("profile_queries".to_string())
1116 }
1117
1118 translation
1119 }
1120
1121 fn escape_dep_filename(filename: &FileName) -> String {
1122 // Apparently clang and gcc *only* escape spaces:
1123 // http://llvm.org/klaus/clang/commit/9d50634cfc268ecc9a7250226dd5ca0e945240d4
1124 filename.to_string().replace(" ", "\\ ")
1125 }
1126
1127 // Returns all the paths that correspond to generated files.
1128 fn generated_output_paths(sess: &Session,
1129 outputs: &OutputFilenames,
1130 exact_name: bool,
1131 crate_name: &str) -> Vec<PathBuf> {
1132 let mut out_filenames = Vec::new();
1133 for output_type in sess.opts.output_types.keys() {
1134 let file = outputs.path(*output_type);
1135 match *output_type {
1136 // If the filename has been overridden using `-o`, it will not be modified
1137 // by appending `.rlib`, `.exe`, etc., so we can skip this transformation.
1138 OutputType::Exe if !exact_name => {
1139 for crate_type in sess.crate_types.borrow().iter() {
1140 let p = ::rustc_trans_utils::link::filename_for_input(
1141 sess,
1142 *crate_type,
1143 crate_name,
1144 outputs
1145 );
1146 out_filenames.push(p);
1147 }
1148 }
1149 OutputType::DepInfo if sess.opts.debugging_opts.dep_info_omit_d_target => {
1150 // Don't add the dep-info output when omitting it from dep-info targets
1151 }
1152 _ => {
1153 out_filenames.push(file);
1154 }
1155 }
1156 }
1157 out_filenames
1158 }
1159
1160 // Runs `f` on every output file path and returns the first non-None result, or None if `f`
1161 // returns None for every file path.
1162 fn check_output<F, T>(output_paths: &Vec<PathBuf>, f: F) -> Option<T>
1163 where F: Fn(&PathBuf) -> Option<T> {
1164 for output_path in output_paths {
1165 if let Some(result) = f(output_path) {
1166 return Some(result);
1167 }
1168 }
1169 None
1170 }
1171
1172 pub fn output_contains_path(output_paths: &Vec<PathBuf>, input_path: &PathBuf) -> bool {
1173 let input_path = input_path.canonicalize().ok();
1174 if input_path.is_none() {
1175 return false
1176 }
1177 let check = |output_path: &PathBuf| {
1178 if output_path.canonicalize().ok() == input_path {
1179 Some(())
1180 } else { None }
1181 };
1182 check_output(output_paths, check).is_some()
1183 }
1184
1185 pub fn output_conflicts_with_dir(output_paths: &Vec<PathBuf>) -> Option<PathBuf> {
1186 let check = |output_path: &PathBuf| {
1187 if output_path.is_dir() {
1188 Some(output_path.clone())
1189 } else { None }
1190 };
1191 check_output(output_paths, check)
1192 }
1193
1194 fn write_out_deps(sess: &Session,
1195 outputs: &OutputFilenames,
1196 out_filenames: &Vec<PathBuf>) {
1197 // Write out dependency rules to the dep-info file if requested
1198 if !sess.opts.output_types.contains_key(&OutputType::DepInfo) {
1199 return;
1200 }
1201 let deps_filename = outputs.path(OutputType::DepInfo);
1202
1203 let result =
1204 (|| -> io::Result<()> {
1205 // Build a list of files used to compile the output and
1206 // write Makefile-compatible dependency rules
1207 let files: Vec<String> = sess.codemap()
1208 .files()
1209 .iter()
1210 .filter(|fmap| fmap.is_real_file())
1211 .filter(|fmap| !fmap.is_imported())
1212 .map(|fmap| escape_dep_filename(&fmap.name))
1213 .collect();
1214 let mut file = fs::File::create(&deps_filename)?;
1215 for path in out_filenames {
1216 write!(file, "{}: {}\n\n", path.display(), files.join(" "))?;
1217 }
1218
1219 // Emit a fake target for each input file to the compilation. This
1220 // prevents `make` from spitting out an error if a file is later
1221 // deleted. For more info see #28735
1222 for path in files {
1223 writeln!(file, "{}:", path)?;
1224 }
1225 Ok(())
1226 })();
1227
1228 match result {
1229 Ok(()) => {}
1230 Err(e) => {
1231 sess.fatal(&format!("error writing dependencies to `{}`: {}",
1232 deps_filename.display(),
1233 e));
1234 }
1235 }
1236 }
1237
1238 pub fn collect_crate_types(session: &Session, attrs: &[ast::Attribute]) -> Vec<config::CrateType> {
1239 // Unconditionally collect crate types from attributes to make them used
1240 let attr_types: Vec<config::CrateType> =
1241 attrs.iter()
1242 .filter_map(|a| {
1243 if a.check_name("crate_type") {
1244 match a.value_str() {
1245 Some(ref n) if *n == "rlib" => {
1246 Some(config::CrateTypeRlib)
1247 }
1248 Some(ref n) if *n == "dylib" => {
1249 Some(config::CrateTypeDylib)
1250 }
1251 Some(ref n) if *n == "cdylib" => {
1252 Some(config::CrateTypeCdylib)
1253 }
1254 Some(ref n) if *n == "lib" => {
1255 Some(config::default_lib_output())
1256 }
1257 Some(ref n) if *n == "staticlib" => {
1258 Some(config::CrateTypeStaticlib)
1259 }
1260 Some(ref n) if *n == "proc-macro" => {
1261 Some(config::CrateTypeProcMacro)
1262 }
1263 Some(ref n) if *n == "bin" => Some(config::CrateTypeExecutable),
1264 Some(_) => {
1265 session.buffer_lint(lint::builtin::UNKNOWN_CRATE_TYPES,
1266 ast::CRATE_NODE_ID,
1267 a.span,
1268 "invalid `crate_type` value");
1269 None
1270 }
1271 _ => {
1272 session.struct_span_err(a.span, "`crate_type` requires a value")
1273 .note("for example: `#![crate_type=\"lib\"]`")
1274 .emit();
1275 None
1276 }
1277 }
1278 } else {
1279 None
1280 }
1281 })
1282 .collect();
1283
1284 // If we're generating a test executable, then ignore all other output
1285 // styles at all other locations
1286 if session.opts.test {
1287 return vec![config::CrateTypeExecutable];
1288 }
1289
1290 // Only check command line flags if present. If no types are specified by
1291 // command line, then reuse the empty `base` Vec to hold the types that
1292 // will be found in crate attributes.
1293 let mut base = session.opts.crate_types.clone();
1294 if base.is_empty() {
1295 base.extend(attr_types);
1296 if base.is_empty() {
1297 base.push(::rustc_trans_utils::link::default_output_for_target(session));
1298 }
1299 base.sort();
1300 base.dedup();
1301 }
1302
1303 base.into_iter()
1304 .filter(|crate_type| {
1305 let res = !::rustc_trans_utils::link::invalid_output_for_target(session, *crate_type);
1306
1307 if !res {
1308 session.warn(&format!("dropping unsupported crate type `{}` for target `{}`",
1309 *crate_type,
1310 session.opts.target_triple));
1311 }
1312
1313 res
1314 })
1315 .collect()
1316 }
1317
1318 pub fn compute_crate_disambiguator(session: &Session) -> CrateDisambiguator {
1319 use std::hash::Hasher;
1320
1321 // The crate_disambiguator is a 128 bit hash. The disambiguator is fed
1322 // into various other hashes quite a bit (symbol hashes, incr. comp. hashes,
1323 // debuginfo type IDs, etc), so we don't want it to be too wide. 128 bits
1324 // should still be safe enough to avoid collisions in practice.
1325 let mut hasher = StableHasher::<Fingerprint>::new();
1326
1327 let mut metadata = session.opts.cg.metadata.clone();
1328 // We don't want the crate_disambiguator to dependent on the order
1329 // -C metadata arguments, so sort them:
1330 metadata.sort();
1331 // Every distinct -C metadata value is only incorporated once:
1332 metadata.dedup();
1333
1334 hasher.write(b"metadata");
1335 for s in &metadata {
1336 // Also incorporate the length of a metadata string, so that we generate
1337 // different values for `-Cmetadata=ab -Cmetadata=c` and
1338 // `-Cmetadata=a -Cmetadata=bc`
1339 hasher.write_usize(s.len());
1340 hasher.write(s.as_bytes());
1341 }
1342
1343 // Also incorporate crate type, so that we don't get symbol conflicts when
1344 // linking against a library of the same name, if this is an executable.
1345 let is_exe = session.crate_types.borrow().contains(&config::CrateTypeExecutable);
1346 hasher.write(if is_exe { b"exe" } else { b"lib" });
1347
1348 CrateDisambiguator::from(hasher.finish())
1349
1350 }
1351
1352 pub fn build_output_filenames(input: &Input,
1353 odir: &Option<PathBuf>,
1354 ofile: &Option<PathBuf>,
1355 attrs: &[ast::Attribute],
1356 sess: &Session)
1357 -> OutputFilenames {
1358 match *ofile {
1359 None => {
1360 // "-" as input file will cause the parser to read from stdin so we
1361 // have to make up a name
1362 // We want to toss everything after the final '.'
1363 let dirpath = match *odir {
1364 Some(ref d) => d.clone(),
1365 None => PathBuf::new(),
1366 };
1367
1368 // If a crate name is present, we use it as the link name
1369 let stem = sess.opts
1370 .crate_name
1371 .clone()
1372 .or_else(|| attr::find_crate_name(attrs).map(|n| n.to_string()))
1373 .unwrap_or(input.filestem());
1374
1375 OutputFilenames {
1376 out_directory: dirpath,
1377 out_filestem: stem,
1378 single_output_file: None,
1379 extra: sess.opts.cg.extra_filename.clone(),
1380 outputs: sess.opts.output_types.clone(),
1381 }
1382 }
1383
1384 Some(ref out_file) => {
1385 let unnamed_output_types = sess.opts
1386 .output_types
1387 .values()
1388 .filter(|a| a.is_none())
1389 .count();
1390 let ofile = if unnamed_output_types > 1 {
1391 sess.warn("due to multiple output types requested, the explicitly specified \
1392 output file name will be adapted for each output type");
1393 None
1394 } else {
1395 Some(out_file.clone())
1396 };
1397 if *odir != None {
1398 sess.warn("ignoring --out-dir flag due to -o flag");
1399 }
1400 if !sess.opts.cg.extra_filename.is_empty() {
1401 sess.warn("ignoring -C extra-filename flag due to -o flag");
1402 }
1403
1404 let cur_dir = Path::new("");
1405
1406 OutputFilenames {
1407 out_directory: out_file.parent().unwrap_or(cur_dir).to_path_buf(),
1408 out_filestem: out_file.file_stem()
1409 .unwrap_or(OsStr::new(""))
1410 .to_str()
1411 .unwrap()
1412 .to_string(),
1413 single_output_file: ofile,
1414 extra: sess.opts.cg.extra_filename.clone(),
1415 outputs: sess.opts.output_types.clone(),
1416 }
1417 }
1418 }
1419 }