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