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.
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.
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
;
17 use rustc
::session
::{Session, CompileResult, CrateDisambiguator}
;
18 use rustc
::session
::CompileIncomplete
;
19 use rustc
::session
::config
::{self, Input, OutputFilenames, OutputType}
;
20 use rustc
::session
::search_paths
::PathKind
;
22 use rustc
::middle
::{self, stability, reachable, resolve_lifetime}
;
23 use rustc
::middle
::cstore
::CrateStore
;
24 use rustc
::middle
::privacy
::AccessLevels
;
25 use rustc
::ty
::{self, TyCtxt, Resolutions, AllArenas}
;
27 use rustc
::util
::common
::{ErrorReported, time}
;
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_trans_utils
::trans_crate
::TransCrate
;
35 use rustc_typeck
as typeck
;
37 use rustc_plugin
::registry
::Registry
;
38 use rustc_plugin
as plugin
;
39 use rustc_passes
::{self, ast_validation, loops, consts, static_recursion, hir_stats}
;
40 use rustc_const_eval
::{self, check_match}
;
41 use super::Compilation
;
47 use std
::ffi
::{OsString, OsStr}
;
49 use std
::io
::{self, Write}
;
51 use std
::path
::{Path, PathBuf}
;
54 use syntax
::{self, ast, attr, diagnostics, visit}
;
55 use syntax
::ext
::base
::ExtCtxt
;
56 use syntax
::fold
::Folder
;
57 use syntax
::parse
::{self, PResult}
;
58 use syntax
::util
::node_count
::NodeCounter
;
59 use syntax_pos
::FileName
;
63 use pretty
::ReplaceBodyWithLoop
;
67 pub fn compile_input(trans
: Box
<TransCrate
>,
70 input_path
: &Option
<PathBuf
>,
72 outdir
: &Option
<PathBuf
>,
73 output
: &Option
<PathBuf
>,
74 addl_plugins
: Option
<Vec
<String
>>,
75 control
: &CompileController
) -> CompileResult
{
76 macro_rules
! controller_entry_point
{
77 ($point
: ident
, $tsess
: expr
, $make_state
: expr
, $phase_result
: expr
) => {{
78 let state
= &mut $make_state
;
79 let phase_result
: &CompileResult
= &$phase_result
;
80 if phase_result
.is_ok() || control
.$point
.run_callback_on_error
{
81 (control
.$point
.callback
)(state
);
84 if control
.$point
.stop
== Compilation
::Stop
{
85 // FIXME: shouldn't this return Err(CompileIncomplete::Stopped)
86 // if there are no errors?
87 return $tsess
.compile_status();
92 if sess
.profile_queries() {
96 // We need nested scopes here, because the intermediate results can keep
97 // large chunks of memory alive and we want to free them as soon as
98 // possible to keep the peak memory usage low
99 let (outputs
, ongoing_trans
, dep_graph
) = {
100 let krate
= match phase_1_parse_input(control
, sess
, input
) {
102 Err(mut parse_error
) => {
104 return Err(CompileIncomplete
::Errored(ErrorReported
));
108 let (krate
, registry
) = {
109 let mut compile_state
= CompileState
::state_after_parse(input
,
115 controller_entry_point
!(after_parse
,
120 (compile_state
.krate
.unwrap(), compile_state
.registry
)
123 let outputs
= build_output_filenames(input
, outdir
, output
, &krate
.attrs
, sess
);
125 ::rustc_trans_utils
::link
::find_crate_name(Some(sess
), &krate
.attrs
, input
);
126 let ExpansionResult { expanded_crate, defs, analysis, resolutions, mut hir_forest }
= {
127 phase_2_configure_and_expand(
134 control
.make_glob_map
,
136 let mut state
= CompileState
::state_after_expand(
137 input
, sess
, outdir
, output
, &cstore
, expanded_crate
, &crate_name
,
139 controller_entry_point
!(after_expand
, sess
, state
, Ok(()));
145 let output_paths
= generated_output_paths(sess
, &outputs
, output
.is_some(), &crate_name
);
147 // Ensure the source file isn't accidentally overwritten during compilation.
148 if let Some(ref input_path
) = *input_path
{
149 if sess
.opts
.will_create_output_file() {
150 if output_contains_path(&output_paths
, input_path
) {
152 "the input file \"{}\" would be overwritten by the generated \
154 input_path
.display()));
155 return Err(CompileIncomplete
::Stopped
);
157 if let Some(dir_path
) = output_conflicts_with_dir(&output_paths
) {
159 "the generated executable for the input file \"{}\" conflicts with the \
160 existing directory \"{}\"",
161 input_path
.display(), dir_path
.display()));
162 return Err(CompileIncomplete
::Stopped
);
167 write_out_deps(sess
, &outputs
, &output_paths
);
168 if sess
.opts
.output_types
.contains_key(&OutputType
::DepInfo
) &&
169 sess
.opts
.output_types
.keys().count() == 1 {
173 if let &Some(ref dir
) = outdir
{
174 if fs
::create_dir_all(dir
).is_err() {
175 sess
.err("failed to find or create the directory specified by --out-dir");
176 return Err(CompileIncomplete
::Stopped
);
180 let arenas
= AllArenas
::new();
182 // Construct the HIR map
183 let hir_map
= time(sess
.time_passes(),
185 || hir_map
::map_crate(sess
, cstore
, &mut hir_forest
, &defs
));
188 hir_map
.dep_graph
.assert_ignored();
189 controller_entry_point
!(after_hir_lowering
,
191 CompileState
::state_after_hir_lowering(input
,
207 let opt_crate
= if control
.keep_ast
{
208 Some(&expanded_crate
)
210 drop(expanded_crate
);
214 phase_3_run_analysis_passes(&*trans
,
224 |tcx
, analysis
, rx
, result
| {
226 // Eventually, we will want to track plugins.
227 tcx
.dep_graph
.with_ignore(|| {
228 let mut state
= CompileState
::state_after_analysis(input
,
237 (control
.after_analysis
.callback
)(&mut state
);
240 if control
.after_analysis
.stop
== Compilation
::Stop
{
241 return result
.and_then(|_
| Err(CompileIncomplete
::Stopped
));
247 if log_enabled
!(::log
::Level
::Info
) {
248 println
!("Pre-trans");
249 tcx
.print_debug_stats();
252 let ongoing_trans
= phase_4_translate_to_llvm(&*trans
, tcx
, rx
);
254 if log_enabled
!(::log
::Level
::Info
) {
255 println
!("Post-trans");
256 tcx
.print_debug_stats();
259 if tcx
.sess
.opts
.output_types
.contains_key(&OutputType
::Mir
) {
260 if let Err(e
) = mir
::transform
::dump_mir
::emit_mir(tcx
, &outputs
) {
261 sess
.err(&format
!("could not emit MIR: {}", e
));
262 sess
.abort_if_errors();
266 Ok((outputs
.clone(), ongoing_trans
, tcx
.dep_graph
.clone()))
270 if sess
.opts
.debugging_opts
.print_type_sizes
{
271 sess
.code_stats
.borrow().print_type_sizes();
274 trans
.join_trans_and_link(ongoing_trans
, sess
, &dep_graph
, &outputs
)?
;
276 if sess
.opts
.debugging_opts
.perf_stats
{
277 sess
.print_perf_stats();
280 controller_entry_point
!(
283 CompileState
::state_when_compilation_done(input
, sess
, outdir
, output
),
290 pub fn source_name(input
: &Input
) -> FileName
{
292 Input
::File(ref ifile
) => ifile
.clone().into(),
293 Input
::Str { ref name, .. }
=> name
.clone(),
297 /// CompileController is used to customize compilation, it allows compilation to
298 /// be stopped and/or to call arbitrary code at various points in compilation.
299 /// It also allows for various flags to be set to influence what information gets
300 /// collected during compilation.
302 /// This is a somewhat higher level controller than a Session - the Session
303 /// controls what happens in each phase, whereas the CompileController controls
304 /// whether a phase is run at all and whether other code (from outside the
305 /// compiler) is run between phases.
307 /// Note that if compilation is set to stop and a callback is provided for a
308 /// given entry point, the callback is called before compilation is stopped.
310 /// Expect more entry points to be added in the future.
311 pub struct CompileController
<'a
> {
312 pub after_parse
: PhaseController
<'a
>,
313 pub after_expand
: PhaseController
<'a
>,
314 pub after_hir_lowering
: PhaseController
<'a
>,
315 pub after_analysis
: PhaseController
<'a
>,
316 pub compilation_done
: PhaseController
<'a
>,
318 // FIXME we probably want to group the below options together and offer a
319 // better API, rather than this ad-hoc approach.
320 pub make_glob_map
: MakeGlobMap
,
321 // Whether the compiler should keep the ast beyond parsing.
323 // -Zcontinue-parse-after-error
324 pub continue_parse_after_error
: bool
,
326 /// Allows overriding default rustc query providers,
327 /// after `default_provide` has installed them.
328 pub provide
: Box
<Fn(&mut ty
::maps
::Providers
) + 'a
>,
329 /// Same as `provide`, but only for non-local crates,
330 /// applied after `default_provide_extern`.
331 pub provide_extern
: Box
<Fn(&mut ty
::maps
::Providers
) + 'a
>,
334 impl<'a
> CompileController
<'a
> {
335 pub fn basic() -> CompileController
<'a
> {
337 after_parse
: PhaseController
::basic(),
338 after_expand
: PhaseController
::basic(),
339 after_hir_lowering
: PhaseController
::basic(),
340 after_analysis
: PhaseController
::basic(),
341 compilation_done
: PhaseController
::basic(),
342 make_glob_map
: MakeGlobMap
::No
,
344 continue_parse_after_error
: false,
346 provide_extern
: box |_
| {}
,
351 pub struct PhaseController
<'a
> {
352 pub stop
: Compilation
,
353 // If true then the compiler will try to run the callback even if the phase
354 // ends with an error. Note that this is not always possible.
355 pub run_callback_on_error
: bool
,
356 pub callback
: Box
<Fn(&mut CompileState
) + 'a
>,
359 impl<'a
> PhaseController
<'a
> {
360 pub fn basic() -> PhaseController
<'a
> {
362 stop
: Compilation
::Continue
,
363 run_callback_on_error
: false,
364 callback
: box |_
| {}
,
369 /// State that is passed to a callback. What state is available depends on when
370 /// during compilation the callback is made. See the various constructor methods
371 /// (`state_*`) in the impl to see which data is provided for any given entry point.
372 pub struct CompileState
<'a
, 'tcx
: 'a
> {
373 pub input
: &'a Input
,
374 pub session
: &'tcx Session
,
375 pub krate
: Option
<ast
::Crate
>,
376 pub registry
: Option
<Registry
<'a
>>,
377 pub cstore
: Option
<&'tcx CStore
>,
378 pub crate_name
: Option
<&'a
str>,
379 pub output_filenames
: Option
<&'a OutputFilenames
>,
380 pub out_dir
: Option
<&'a Path
>,
381 pub out_file
: Option
<&'a Path
>,
382 pub arenas
: Option
<&'tcx AllArenas
<'tcx
>>,
383 pub expanded_crate
: Option
<&'a ast
::Crate
>,
384 pub hir_crate
: Option
<&'a hir
::Crate
>,
385 pub hir_map
: Option
<&'a hir_map
::Map
<'tcx
>>,
386 pub resolutions
: Option
<&'a Resolutions
>,
387 pub analysis
: Option
<&'a ty
::CrateAnalysis
>,
388 pub tcx
: Option
<TyCtxt
<'a
, 'tcx
, 'tcx
>>,
391 impl<'a
, 'tcx
> CompileState
<'a
, 'tcx
> {
392 fn empty(input
: &'a Input
,
393 session
: &'tcx Session
,
394 out_dir
: &'a Option
<PathBuf
>)
399 out_dir
: out_dir
.as_ref().map(|s
| &**s
),
406 output_filenames
: None
,
407 expanded_crate
: None
,
416 fn state_after_parse(input
: &'a Input
,
417 session
: &'tcx Session
,
418 out_dir
: &'a Option
<PathBuf
>,
419 out_file
: &'a Option
<PathBuf
>,
421 cstore
: &'tcx CStore
)
424 // Initialize the registry before moving `krate`
425 registry
: Some(Registry
::new(&session
, krate
.span
)),
427 cstore
: Some(cstore
),
428 out_file
: out_file
.as_ref().map(|s
| &**s
),
429 ..CompileState
::empty(input
, session
, out_dir
)
433 fn state_after_expand(input
: &'a Input
,
434 session
: &'tcx Session
,
435 out_dir
: &'a Option
<PathBuf
>,
436 out_file
: &'a Option
<PathBuf
>,
437 cstore
: &'tcx CStore
,
438 expanded_crate
: &'a ast
::Crate
,
442 crate_name
: Some(crate_name
),
443 cstore
: Some(cstore
),
444 expanded_crate
: Some(expanded_crate
),
445 out_file
: out_file
.as_ref().map(|s
| &**s
),
446 ..CompileState
::empty(input
, session
, out_dir
)
450 fn state_after_hir_lowering(input
: &'a Input
,
451 session
: &'tcx Session
,
452 out_dir
: &'a Option
<PathBuf
>,
453 out_file
: &'a Option
<PathBuf
>,
454 arenas
: &'tcx AllArenas
<'tcx
>,
455 cstore
: &'tcx CStore
,
456 hir_map
: &'a hir_map
::Map
<'tcx
>,
457 analysis
: &'a ty
::CrateAnalysis
,
458 resolutions
: &'a Resolutions
,
459 krate
: &'a ast
::Crate
,
460 hir_crate
: &'a hir
::Crate
,
461 output_filenames
: &'a OutputFilenames
,
465 crate_name
: Some(crate_name
),
466 arenas
: Some(arenas
),
467 cstore
: Some(cstore
),
468 hir_map
: Some(hir_map
),
469 analysis
: Some(analysis
),
470 resolutions
: Some(resolutions
),
471 expanded_crate
: Some(krate
),
472 hir_crate
: Some(hir_crate
),
473 output_filenames
: Some(output_filenames
),
474 out_file
: out_file
.as_ref().map(|s
| &**s
),
475 ..CompileState
::empty(input
, session
, out_dir
)
479 fn state_after_analysis(input
: &'a Input
,
480 session
: &'tcx Session
,
481 out_dir
: &'a Option
<PathBuf
>,
482 out_file
: &'a Option
<PathBuf
>,
483 krate
: Option
<&'a ast
::Crate
>,
484 hir_crate
: &'a hir
::Crate
,
485 analysis
: &'a ty
::CrateAnalysis
,
486 tcx
: TyCtxt
<'a
, 'tcx
, 'tcx
>,
490 analysis
: Some(analysis
),
492 expanded_crate
: krate
,
493 hir_crate
: Some(hir_crate
),
494 crate_name
: Some(crate_name
),
495 out_file
: out_file
.as_ref().map(|s
| &**s
),
496 ..CompileState
::empty(input
, session
, out_dir
)
500 fn state_when_compilation_done(input
: &'a Input
,
501 session
: &'tcx Session
,
502 out_dir
: &'a Option
<PathBuf
>,
503 out_file
: &'a Option
<PathBuf
>)
506 out_file
: out_file
.as_ref().map(|s
| &**s
),
507 ..CompileState
::empty(input
, session
, out_dir
)
512 pub fn phase_1_parse_input
<'a
>(control
: &CompileController
,
515 -> PResult
<'a
, ast
::Crate
> {
516 sess
.diagnostic().set_continue_after_error(control
.continue_parse_after_error
);
518 if sess
.profile_queries() {
522 let krate
= time(sess
.time_passes(), "parsing", || {
524 Input
::File(ref file
) => {
525 parse
::parse_crate_from_file(file
, &sess
.parse_sess
)
527 Input
::Str { ref input, ref name }
=> {
528 parse
::parse_crate_from_source_str(name
.clone(),
535 sess
.diagnostic().set_continue_after_error(true);
537 if sess
.opts
.debugging_opts
.ast_json_noexpand
{
538 println
!("{}", json
::as_json(&krate
));
541 if sess
.opts
.debugging_opts
.input_stats
{
542 println
!("Lines of code: {}", sess
.codemap().count_lines());
543 println
!("Pre-expansion node count: {}", count_nodes(&krate
));
546 if let Some(ref s
) = sess
.opts
.debugging_opts
.show_span
{
547 syntax
::show_span
::run(sess
.diagnostic(), s
, &krate
);
550 if sess
.opts
.debugging_opts
.hir_stats
{
551 hir_stats
::print_ast_stats(&krate
, "PRE EXPANSION AST STATS");
557 fn count_nodes(krate
: &ast
::Crate
) -> usize {
558 let mut counter
= NodeCounter
::new();
559 visit
::walk_crate(&mut counter
, krate
);
563 // For continuing compilation after a parsed crate has been
566 pub struct ExpansionResult
{
567 pub expanded_crate
: ast
::Crate
,
568 pub defs
: hir_map
::Definitions
,
569 pub analysis
: ty
::CrateAnalysis
,
570 pub resolutions
: Resolutions
,
571 pub hir_forest
: hir_map
::Forest
,
574 pub struct InnerExpansionResult
<'a
> {
575 pub expanded_crate
: ast
::Crate
,
576 pub resolver
: Resolver
<'a
>,
577 pub hir_forest
: hir_map
::Forest
,
580 /// Run the "early phases" of the compiler: initial `cfg` processing,
581 /// loading compiler plugins (including those from `addl_plugins`),
582 /// syntax expansion, secondary `cfg` expansion, synthesis of a test
583 /// harness if one is to be provided, injection of a dependency on the
584 /// standard library and prelude, and name resolution.
586 /// Returns `None` if we're aborting after handling -W help.
587 pub fn phase_2_configure_and_expand
<F
>(sess
: &Session
,
590 registry
: Option
<Registry
>,
592 addl_plugins
: Option
<Vec
<String
>>,
593 make_glob_map
: MakeGlobMap
,
595 -> Result
<ExpansionResult
, CompileIncomplete
>
596 where F
: FnOnce(&ast
::Crate
) -> CompileResult
{
597 // Currently, we ignore the name resolution data structures for the purposes of dependency
598 // tracking. Instead we will run name resolution and include its output in the hash of each
599 // item, much like we do for macro expansion. In other words, the hash reflects not just
600 // its contents but the results of name resolution on those contents. Hopefully we'll push
601 // this back at some point.
602 let mut crate_loader
= CrateLoader
::new(sess
, &cstore
, &crate_name
);
603 let resolver_arenas
= Resolver
::arenas();
604 let result
= phase_2_configure_and_expand_inner(sess
, cstore
, krate
, registry
, crate_name
,
605 addl_plugins
, make_glob_map
, &resolver_arenas
,
606 &mut crate_loader
, after_expand
);
608 Ok(InnerExpansionResult {expanded_crate, resolver, hir_forest}
) => {
611 defs
: resolver
.definitions
,
613 resolutions
: Resolutions
{
614 freevars
: resolver
.freevars
,
615 export_map
: resolver
.export_map
,
616 trait_map
: resolver
.trait_map
,
617 maybe_unused_trait_imports
: resolver
.maybe_unused_trait_imports
,
618 maybe_unused_extern_crates
: resolver
.maybe_unused_extern_crates
,
621 analysis
: ty
::CrateAnalysis
{
622 access_levels
: Rc
::new(AccessLevels
::default()),
623 name
: crate_name
.to_string(),
624 glob_map
: if resolver
.make_glob_map { Some(resolver.glob_map) }
else { None }
,
632 /// Same as phase_2_configure_and_expand, but doesn't let you keep the resolver
634 pub fn phase_2_configure_and_expand_inner
<'a
, F
>(sess
: &'a Session
,
637 registry
: Option
<Registry
>,
639 addl_plugins
: Option
<Vec
<String
>>,
640 make_glob_map
: MakeGlobMap
,
641 resolver_arenas
: &'a ResolverArenas
<'a
>,
642 crate_loader
: &'a
mut CrateLoader
,
644 -> Result
<InnerExpansionResult
<'a
>, CompileIncomplete
>
645 where F
: FnOnce(&ast
::Crate
) -> CompileResult
,
647 let time_passes
= sess
.time_passes();
649 let (mut krate
, features
) = syntax
::config
::features(krate
, &sess
.parse_sess
, sess
.opts
.test
);
650 // these need to be set "early" so that expansion sees `quote` if enabled.
651 *sess
.features
.borrow_mut() = features
;
653 *sess
.crate_types
.borrow_mut() = collect_crate_types(sess
, &krate
.attrs
);
655 let disambiguator
= compute_crate_disambiguator(sess
);
656 *sess
.crate_disambiguator
.borrow_mut() = Some(disambiguator
);
657 rustc_incremental
::prepare_session_directory(
663 if sess
.opts
.incremental
.is_some() {
664 time(time_passes
, "garbage collect incremental cache directory", || {
665 if let Err(e
) = rustc_incremental
::garbage_collect_session_directories(sess
) {
666 warn
!("Error while trying to garbage collect incremental \
667 compilation cache directory: {}", e
);
672 // If necessary, compute the dependency graph (in the background).
673 let future_dep_graph
= if sess
.opts
.build_dep_graph() {
674 Some(rustc_incremental
::load_dep_graph(sess
, time_passes
))
679 time(time_passes
, "recursion limit", || {
680 middle
::recursion_limit
::update_limits(sess
, &krate
);
683 krate
= time(time_passes
, "crate injection", || {
684 let alt_std_name
= sess
.opts
.alt_std_name
.clone();
685 syntax
::std_inject
::maybe_inject_crates_ref(krate
, alt_std_name
)
688 let mut addl_plugins
= Some(addl_plugins
);
689 let registrars
= time(time_passes
, "plugin loading", || {
690 plugin
::load
::load_plugins(sess
,
694 addl_plugins
.take().unwrap())
697 let mut registry
= registry
.unwrap_or(Registry
::new(sess
, krate
.span
));
699 time(time_passes
, "plugin registration", || {
700 if sess
.features
.borrow().rustc_diagnostic_macros
{
701 registry
.register_macro("__diagnostic_used",
702 diagnostics
::plugin
::expand_diagnostic_used
);
703 registry
.register_macro("__register_diagnostic",
704 diagnostics
::plugin
::expand_register_diagnostic
);
705 registry
.register_macro("__build_diagnostic_array",
706 diagnostics
::plugin
::expand_build_diagnostic_array
);
709 for registrar
in registrars
{
710 registry
.args_hidden
= Some(registrar
.args
);
711 (registrar
.fun
)(&mut registry
);
715 let whitelisted_legacy_custom_derives
= registry
.take_whitelisted_custom_derives();
716 let Registry
{ syntax_exts
, early_lint_passes
, late_lint_passes
, lint_groups
,
717 llvm_passes
, attributes
, .. } = registry
;
719 sess
.track_errors(|| {
720 let mut ls
= sess
.lint_store
.borrow_mut();
721 for pass
in early_lint_passes
{
722 ls
.register_early_pass(Some(sess
), true, pass
);
724 for pass
in late_lint_passes
{
725 ls
.register_late_pass(Some(sess
), true, pass
);
728 for (name
, to
) in lint_groups
{
729 ls
.register_group(Some(sess
), true, name
, to
);
732 *sess
.plugin_llvm_passes
.borrow_mut() = llvm_passes
;
733 *sess
.plugin_attributes
.borrow_mut() = attributes
.clone();
736 // Lint plugins are registered; now we can process command line flags.
737 if sess
.opts
.describe_lints
{
738 super::describe_lints(&sess
.lint_store
.borrow(), true);
739 return Err(CompileIncomplete
::Stopped
);
742 let mut resolver
= Resolver
::new(sess
,
749 resolver
.whitelisted_legacy_custom_derives
= whitelisted_legacy_custom_derives
;
750 syntax_ext
::register_builtins(&mut resolver
, syntax_exts
, sess
.features
.borrow().quote
);
752 krate
= time(time_passes
, "expansion", || {
753 // Windows dlls do not have rpaths, so they don't know how to find their
754 // dependencies. It's up to us to tell the system where to find all the
755 // dependent dlls. Note that this uses cfg!(windows) as opposed to
756 // targ_cfg because syntax extensions are always loaded for the host
757 // compiler, not for the target.
759 // This is somewhat of an inherently racy operation, however, as
760 // multiple threads calling this function could possibly continue
761 // extending PATH far beyond what it should. To solve this for now we
762 // just don't add any new elements to PATH which are already there
763 // within PATH. This is basically a targeted fix at #17360 for rustdoc
764 // which runs rustc in parallel but has been seen (#33844) to cause
765 // problems with PATH becoming too long.
766 let mut old_path
= OsString
::new();
768 old_path
= env
::var_os("PATH").unwrap_or(old_path
);
769 let mut new_path
= sess
.host_filesearch(PathKind
::All
)
770 .get_dylib_search_paths();
771 for path
in env
::split_paths(&old_path
) {
772 if !new_path
.contains(&path
) {
777 &env
::join_paths(new_path
.iter()
778 .filter(|p
| env
::join_paths(iter
::once(p
)).is_ok()))
781 let features
= sess
.features
.borrow();
782 let cfg
= syntax
::ext
::expand
::ExpansionConfig
{
783 features
: Some(&features
),
784 recursion_limit
: sess
.recursion_limit
.get(),
785 trace_mac
: sess
.opts
.debugging_opts
.trace_macros
,
786 should_test
: sess
.opts
.test
,
787 ..syntax
::ext
::expand
::ExpansionConfig
::default(crate_name
.to_string())
790 let mut ecx
= ExtCtxt
::new(&sess
.parse_sess
, cfg
, &mut resolver
);
791 let err_count
= ecx
.parse_sess
.span_diagnostic
.err_count();
793 let krate
= ecx
.monotonic_expander().expand_crate(krate
);
795 ecx
.check_unused_macros();
797 let mut missing_fragment_specifiers
: Vec
<_
> =
798 ecx
.parse_sess
.missing_fragment_specifiers
.borrow().iter().cloned().collect();
799 missing_fragment_specifiers
.sort();
800 for span
in missing_fragment_specifiers
{
801 let lint
= lint
::builtin
::MISSING_FRAGMENT_SPECIFIER
;
802 let msg
= "missing fragment specifier";
803 sess
.buffer_lint(lint
, ast
::CRATE_NODE_ID
, span
, msg
);
805 if ecx
.parse_sess
.span_diagnostic
.err_count() - ecx
.resolve_err_count
> err_count
{
806 ecx
.parse_sess
.span_diagnostic
.abort_if_errors();
809 env
::set_var("PATH", &old_path
);
814 krate
= time(time_passes
, "maybe building test harness", || {
815 syntax
::test
::modify_for_testing(&sess
.parse_sess
,
822 // If we're actually rustdoc then there's no need to actually compile
823 // anything, so switch everything to just looping
824 if sess
.opts
.actually_rustdoc
{
825 krate
= ReplaceBodyWithLoop
::new(sess
).fold_crate(krate
);
828 // If we're in rustdoc we're always compiling as an rlib, but that'll trip a
829 // bunch of checks in the `modify` function below. For now just skip this
830 // step entirely if we're rustdoc as it's not too useful anyway.
831 if !sess
.opts
.actually_rustdoc
{
832 krate
= time(time_passes
, "maybe creating a macro crate", || {
833 let crate_types
= sess
.crate_types
.borrow();
834 let num_crate_types
= crate_types
.len();
835 let is_proc_macro_crate
= crate_types
.contains(&config
::CrateTypeProcMacro
);
836 let is_test_crate
= sess
.opts
.test
;
837 syntax_ext
::proc_macro_registrar
::modify(&sess
.parse_sess
,
847 krate
= time(time_passes
, "creating allocators", || {
848 allocator
::expand
::modify(&sess
.parse_sess
,
854 after_expand(&krate
)?
;
856 if sess
.opts
.debugging_opts
.input_stats
{
857 println
!("Post-expansion node count: {}", count_nodes(&krate
));
860 if sess
.opts
.debugging_opts
.hir_stats
{
861 hir_stats
::print_ast_stats(&krate
, "POST EXPANSION AST STATS");
864 if sess
.opts
.debugging_opts
.ast_json
{
865 println
!("{}", json
::as_json(&krate
));
870 || ast_validation
::check_crate(sess
, &krate
));
872 time(time_passes
, "name resolution", || -> CompileResult
{
873 resolver
.resolve_crate(&krate
);
877 if resolver
.found_unresolved_macro
{
878 sess
.parse_sess
.span_diagnostic
.abort_if_errors();
881 // Needs to go *after* expansion to be able to check the results of macro expansion.
882 time(time_passes
, "complete gated feature checking", || {
883 sess
.track_errors(|| {
884 syntax
::feature_gate
::check_crate(&krate
,
886 &sess
.features
.borrow(),
888 sess
.opts
.unstable_features
);
893 // First, we need to collect the dep_graph.
894 let dep_graph
= match future_dep_graph
{
895 None
=> DepGraph
::new_disabled(),
897 let prev_graph
= time(time_passes
, "blocked while dep-graph loading finishes", || {
899 .expect("Could not join with background dep_graph thread")
902 DepGraph
::new(prev_graph
)
905 let hir_forest
= time(time_passes
, "lowering ast -> hir", || {
906 let hir_crate
= lower_crate(sess
, cstore
, &dep_graph
, &krate
, &mut resolver
);
908 if sess
.opts
.debugging_opts
.hir_stats
{
909 hir_stats
::print_hir_stats(&hir_crate
);
912 hir_map
::Forest
::new(hir_crate
, &dep_graph
)
917 || lint
::check_ast_crate(sess
, &krate
));
919 // Discard hygiene data, which isn't required after lowering to HIR.
920 if !sess
.opts
.debugging_opts
.keep_hygiene_data
{
921 syntax
::ext
::hygiene
::clear_markings();
924 Ok(InnerExpansionResult
{
925 expanded_crate
: krate
,
931 pub fn default_provide(providers
: &mut ty
::maps
::Providers
) {
932 borrowck
::provide(providers
);
933 mir
::provide(providers
);
934 reachable
::provide(providers
);
935 resolve_lifetime
::provide(providers
);
936 rustc_privacy
::provide(providers
);
937 typeck
::provide(providers
);
938 ty
::provide(providers
);
939 traits
::provide(providers
);
940 reachable
::provide(providers
);
941 rustc_const_eval
::provide(providers
);
942 rustc_passes
::provide(providers
);
943 middle
::region
::provide(providers
);
944 cstore
::provide(providers
);
945 lint
::provide(providers
);
948 pub fn default_provide_extern(providers
: &mut ty
::maps
::Providers
) {
949 cstore
::provide_extern(providers
);
952 /// Run the resolution, typechecking, region checking and other
953 /// miscellaneous analysis passes on the crate. Return various
954 /// structures carrying the results of the analysis.
955 pub fn phase_3_run_analysis_passes
<'tcx
, F
, R
>(trans
: &TransCrate
,
956 control
: &CompileController
,
958 cstore
: &'tcx CrateStore
,
959 hir_map
: hir_map
::Map
<'tcx
>,
960 mut analysis
: ty
::CrateAnalysis
,
961 resolutions
: Resolutions
,
962 arenas
: &'tcx AllArenas
<'tcx
>,
964 output_filenames
: &OutputFilenames
,
966 -> Result
<R
, CompileIncomplete
>
967 where F
: for<'a
> FnOnce(TyCtxt
<'a
, 'tcx
, 'tcx
>,
969 mpsc
::Receiver
<Box
<Any
+ Send
>>,
972 let time_passes
= sess
.time_passes();
974 let query_result_on_disk_cache
= time(time_passes
,
975 "load query result cache",
976 || rustc_incremental
::load_query_result_cache(sess
));
979 "looking for entry point",
980 || middle
::entry
::find_entry_point(sess
, &hir_map
));
982 sess
.plugin_registrar_fn
.set(time(time_passes
, "looking for plugin registrar", || {
983 plugin
::build
::find_plugin_registrar(sess
.diagnostic(), &hir_map
)
985 sess
.derive_registrar_fn
.set(derive_registrar
::find(&hir_map
));
989 || loops
::check_crate(sess
, &hir_map
));
992 "static item recursion checking",
993 || static_recursion
::check_crate(sess
, &hir_map
))?
;
995 let mut local_providers
= ty
::maps
::Providers
::default();
996 default_provide(&mut local_providers
);
997 trans
.provide(&mut local_providers
);
998 (control
.provide
)(&mut local_providers
);
1000 let mut extern_providers
= local_providers
;
1001 default_provide_extern(&mut extern_providers
);
1002 trans
.provide_extern(&mut extern_providers
);
1003 (control
.provide_extern
)(&mut extern_providers
);
1005 let (tx
, rx
) = mpsc
::channel();
1007 TyCtxt
::create_and_enter(sess
,
1014 query_result_on_disk_cache
,
1019 // Do some initialization of the DepGraph that can only be done with the
1021 rustc_incremental
::dep_graph_tcx_init(tcx
);
1023 time(sess
.time_passes(), "attribute checking", || {
1024 hir
::check_attr
::check_crate(tcx
)
1028 "stability checking",
1029 || stability
::check_unstable_api_usage(tcx
));
1031 // passes are timed inside typeck
1032 match typeck
::check_crate(tcx
) {
1035 f(tcx
, analysis
, rx
, Err(x
));
1042 || consts
::check_crate(tcx
));
1044 analysis
.access_levels
=
1045 time(time_passes
, "privacy checking", || rustc_privacy
::check_crate(tcx
));
1048 "intrinsic checking",
1049 || middle
::intrinsicck
::check_crate(tcx
));
1053 || check_match
::check_crate(tcx
));
1055 // this must run before MIR dump, because
1056 // "not all control paths return a value" is reported here.
1058 // maybe move the check to a MIR pass?
1060 "liveness checking",
1061 || middle
::liveness
::check_crate(tcx
));
1065 || borrowck
::check_crate(tcx
));
1068 "MIR borrow checking",
1069 || for def_id
in tcx
.body_owners() { tcx.mir_borrowck(def_id); }
);
1072 "MIR effect checking",
1073 || for def_id
in tcx
.body_owners() {
1074 mir
::transform
::check_unsafety
::check_unsafety(tcx
, def_id
)
1076 // Avoid overwhelming user with errors if type checking failed.
1077 // I'm not sure how helpful this is, to be honest, but it avoids
1079 // lot of annoying errors in the compile-fail tests (basically,
1080 // lint warnings and so on -- kindck used to do this abort, but
1081 // kindck is gone now). -nmatsakis
1082 if sess
.err_count() > 0 {
1083 return Ok(f(tcx
, analysis
, rx
, sess
.compile_status()));
1086 time(time_passes
, "death checking", || middle
::dead
::check_crate(tcx
));
1088 time(time_passes
, "unused lib feature checking", || {
1089 stability
::check_unused_or_stable_features(tcx
)
1092 time(time_passes
, "lint checking", || lint
::check_crate(tcx
));
1094 return Ok(f(tcx
, analysis
, rx
, tcx
.sess
.compile_status()));
1098 /// Run the translation phase to LLVM, after which the AST and analysis can
1100 pub fn phase_4_translate_to_llvm
<'a
, 'tcx
>(trans
: &TransCrate
,
1101 tcx
: TyCtxt
<'a
, 'tcx
, 'tcx
>,
1102 rx
: mpsc
::Receiver
<Box
<Any
+ Send
>>)
1104 let time_passes
= tcx
.sess
.time_passes();
1107 "resolving dependency formats",
1108 || ::rustc
::middle
::dependency_format
::calculate(tcx
));
1111 time(time_passes
, "translation", move || {
1112 trans
.trans_crate(tcx
, rx
)
1114 if tcx
.sess
.profile_queries() {
1115 profile
::dump("profile_queries".to_string())
1121 fn escape_dep_filename(filename
: &FileName
) -> String
{
1122 // Apparently clang and gcc *only* escape spaces:
1123 // http://llvm.org/klaus/clang/commit/9d50634cfc268ecc9a7250226dd5ca0e945240d4
1124 filename
.to_string().replace(" ", "\\ ")
1127 // Returns all the paths that correspond to generated files.
1128 fn generated_output_paths(sess
: &Session
,
1129 outputs
: &OutputFilenames
,
1131 crate_name
: &str) -> Vec
<PathBuf
> {
1132 let mut out_filenames
= Vec
::new();
1133 for output_type
in sess
.opts
.output_types
.keys() {
1134 let file
= outputs
.path(*output_type
);
1135 match *output_type
{
1136 // If the filename has been overridden using `-o`, it will not be modified
1137 // by appending `.rlib`, `.exe`, etc., so we can skip this transformation.
1138 OutputType
::Exe
if !exact_name
=> {
1139 for crate_type
in sess
.crate_types
.borrow().iter() {
1140 let p
= ::rustc_trans_utils
::link
::filename_for_input(
1146 out_filenames
.push(p
);
1149 OutputType
::DepInfo
if sess
.opts
.debugging_opts
.dep_info_omit_d_target
=> {
1150 // Don't add the dep-info output when omitting it from dep-info targets
1153 out_filenames
.push(file
);
1160 // Runs `f` on every output file path and returns the first non-None result, or None if `f`
1161 // returns None for every file path.
1162 fn check_output
<F
, T
>(output_paths
: &Vec
<PathBuf
>, f
: F
) -> Option
<T
>
1163 where F
: Fn(&PathBuf
) -> Option
<T
> {
1164 for output_path
in output_paths
{
1165 if let Some(result
) = f(output_path
) {
1166 return Some(result
);
1172 pub fn output_contains_path(output_paths
: &Vec
<PathBuf
>, input_path
: &PathBuf
) -> bool
{
1173 let input_path
= input_path
.canonicalize().ok();
1174 if input_path
.is_none() {
1177 let check
= |output_path
: &PathBuf
| {
1178 if output_path
.canonicalize().ok() == input_path
{
1182 check_output(output_paths
, check
).is_some()
1185 pub fn output_conflicts_with_dir(output_paths
: &Vec
<PathBuf
>) -> Option
<PathBuf
> {
1186 let check
= |output_path
: &PathBuf
| {
1187 if output_path
.is_dir() {
1188 Some(output_path
.clone())
1191 check_output(output_paths
, check
)
1194 fn write_out_deps(sess
: &Session
,
1195 outputs
: &OutputFilenames
,
1196 out_filenames
: &Vec
<PathBuf
>) {
1197 // Write out dependency rules to the dep-info file if requested
1198 if !sess
.opts
.output_types
.contains_key(&OutputType
::DepInfo
) {
1201 let deps_filename
= outputs
.path(OutputType
::DepInfo
);
1204 (|| -> io
::Result
<()> {
1205 // Build a list of files used to compile the output and
1206 // write Makefile-compatible dependency rules
1207 let files
: Vec
<String
> = sess
.codemap()
1210 .filter(|fmap
| fmap
.is_real_file())
1211 .filter(|fmap
| !fmap
.is_imported())
1212 .map(|fmap
| escape_dep_filename(&fmap
.name
))
1214 let mut file
= fs
::File
::create(&deps_filename
)?
;
1215 for path
in out_filenames
{
1216 write
!(file
, "{}: {}\n\n", path
.display(), files
.join(" "))?
;
1219 // Emit a fake target for each input file to the compilation. This
1220 // prevents `make` from spitting out an error if a file is later
1221 // deleted. For more info see #28735
1223 writeln
!(file
, "{}:", path
)?
;
1231 sess
.fatal(&format
!("error writing dependencies to `{}`: {}",
1232 deps_filename
.display(),
1238 pub fn collect_crate_types(session
: &Session
, attrs
: &[ast
::Attribute
]) -> Vec
<config
::CrateType
> {
1239 // Unconditionally collect crate types from attributes to make them used
1240 let attr_types
: Vec
<config
::CrateType
> =
1243 if a
.check_name("crate_type") {
1244 match a
.value_str() {
1245 Some(ref n
) if *n
== "rlib" => {
1246 Some(config
::CrateTypeRlib
)
1248 Some(ref n
) if *n
== "dylib" => {
1249 Some(config
::CrateTypeDylib
)
1251 Some(ref n
) if *n
== "cdylib" => {
1252 Some(config
::CrateTypeCdylib
)
1254 Some(ref n
) if *n
== "lib" => {
1255 Some(config
::default_lib_output())
1257 Some(ref n
) if *n
== "staticlib" => {
1258 Some(config
::CrateTypeStaticlib
)
1260 Some(ref n
) if *n
== "proc-macro" => {
1261 Some(config
::CrateTypeProcMacro
)
1263 Some(ref n
) if *n
== "bin" => Some(config
::CrateTypeExecutable
),
1265 session
.buffer_lint(lint
::builtin
::UNKNOWN_CRATE_TYPES
,
1268 "invalid `crate_type` value");
1272 session
.struct_span_err(a
.span
, "`crate_type` requires a value")
1273 .note("for example: `#![crate_type=\"lib\"]`")
1284 // If we're generating a test executable, then ignore all other output
1285 // styles at all other locations
1286 if session
.opts
.test
{
1287 return vec
![config
::CrateTypeExecutable
];
1290 // Only check command line flags if present. If no types are specified by
1291 // command line, then reuse the empty `base` Vec to hold the types that
1292 // will be found in crate attributes.
1293 let mut base
= session
.opts
.crate_types
.clone();
1294 if base
.is_empty() {
1295 base
.extend(attr_types
);
1296 if base
.is_empty() {
1297 base
.push(::rustc_trans_utils
::link
::default_output_for_target(session
));
1304 .filter(|crate_type
| {
1305 let res
= !::rustc_trans_utils
::link
::invalid_output_for_target(session
, *crate_type
);
1308 session
.warn(&format
!("dropping unsupported crate type `{}` for target `{}`",
1310 session
.opts
.target_triple
));
1318 pub fn compute_crate_disambiguator(session
: &Session
) -> CrateDisambiguator
{
1319 use std
::hash
::Hasher
;
1321 // The crate_disambiguator is a 128 bit hash. The disambiguator is fed
1322 // into various other hashes quite a bit (symbol hashes, incr. comp. hashes,
1323 // debuginfo type IDs, etc), so we don't want it to be too wide. 128 bits
1324 // should still be safe enough to avoid collisions in practice.
1325 let mut hasher
= StableHasher
::<Fingerprint
>::new();
1327 let mut metadata
= session
.opts
.cg
.metadata
.clone();
1328 // We don't want the crate_disambiguator to dependent on the order
1329 // -C metadata arguments, so sort them:
1331 // Every distinct -C metadata value is only incorporated once:
1334 hasher
.write(b
"metadata");
1335 for s
in &metadata
{
1336 // Also incorporate the length of a metadata string, so that we generate
1337 // different values for `-Cmetadata=ab -Cmetadata=c` and
1338 // `-Cmetadata=a -Cmetadata=bc`
1339 hasher
.write_usize(s
.len());
1340 hasher
.write(s
.as_bytes());
1343 // Also incorporate crate type, so that we don't get symbol conflicts when
1344 // linking against a library of the same name, if this is an executable.
1345 let is_exe
= session
.crate_types
.borrow().contains(&config
::CrateTypeExecutable
);
1346 hasher
.write(if is_exe { b"exe" }
else { b"lib" }
);
1348 CrateDisambiguator
::from(hasher
.finish())
1352 pub fn build_output_filenames(input
: &Input
,
1353 odir
: &Option
<PathBuf
>,
1354 ofile
: &Option
<PathBuf
>,
1355 attrs
: &[ast
::Attribute
],
1357 -> OutputFilenames
{
1360 // "-" as input file will cause the parser to read from stdin so we
1361 // have to make up a name
1362 // We want to toss everything after the final '.'
1363 let dirpath
= match *odir
{
1364 Some(ref d
) => d
.clone(),
1365 None
=> PathBuf
::new(),
1368 // If a crate name is present, we use it as the link name
1369 let stem
= sess
.opts
1372 .or_else(|| attr
::find_crate_name(attrs
).map(|n
| n
.to_string()))
1373 .unwrap_or(input
.filestem());
1376 out_directory
: dirpath
,
1378 single_output_file
: None
,
1379 extra
: sess
.opts
.cg
.extra_filename
.clone(),
1380 outputs
: sess
.opts
.output_types
.clone(),
1384 Some(ref out_file
) => {
1385 let unnamed_output_types
= sess
.opts
1388 .filter(|a
| a
.is_none())
1390 let ofile
= if unnamed_output_types
> 1 {
1391 sess
.warn("due to multiple output types requested, the explicitly specified \
1392 output file name will be adapted for each output type");
1395 Some(out_file
.clone())
1398 sess
.warn("ignoring --out-dir flag due to -o flag");
1400 if !sess
.opts
.cg
.extra_filename
.is_empty() {
1401 sess
.warn("ignoring -C extra-filename flag due to -o flag");
1404 let cur_dir
= Path
::new("");
1407 out_directory
: out_file
.parent().unwrap_or(cur_dir
).to_path_buf(),
1408 out_filestem
: out_file
.file_stem()
1409 .unwrap_or(OsStr
::new(""))
1413 single_output_file
: ofile
,
1414 extra
: sess
.opts
.cg
.extra_filename
.clone(),
1415 outputs
: sess
.opts
.output_types
.clone(),