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