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