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