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