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