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