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