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