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