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.
12 use rustc
::front
::map
as hir_map
;
14 use rustc_mir
::mir_map
::MirMap
;
15 use rustc
::session
::Session
;
16 use rustc
::session
::config
::{self, Input, OutputFilenames, OutputType}
;
17 use rustc
::session
::search_paths
::PathKind
;
19 use rustc
::middle
::{stability, ty, reachable}
;
20 use rustc
::middle
::dependency_format
;
22 use rustc
::util
::common
::time
;
23 use rustc_borrowck
as borrowck
;
24 use rustc_resolve
as resolve
;
25 use rustc_metadata
::macro_import
;
26 use rustc_metadata
::creader
::LocalCrateReader
;
27 use rustc_metadata
::cstore
::CStore
;
28 use rustc_trans
::back
::link
;
29 use rustc_trans
::back
::write
;
30 use rustc_trans
::trans
;
31 use rustc_typeck
as typeck
;
33 use rustc_plugin
::registry
::Registry
;
34 use rustc_plugin
as plugin
;
36 use rustc_front
::lowering
::{lower_crate, LoweringContext}
;
37 use super::Compilation
;
41 use std
::collections
::HashMap
;
43 use std
::ffi
::{OsString, OsStr}
;
45 use std
::io
::{self, Write}
;
46 use std
::path
::{Path, PathBuf}
;
47 use syntax
::ast
::{self, NodeIdAssigner}
;
49 use syntax
::attr
::AttrMetaMethods
;
50 use syntax
::diagnostics
;
51 use syntax
::fold
::Folder
;
53 use syntax
::parse
::token
;
54 use syntax
::util
::node_count
::NodeCounter
;
59 pub fn compile_input(sess
: Session
,
61 cfg
: ast
::CrateConfig
,
63 outdir
: &Option
<PathBuf
>,
64 output
: &Option
<PathBuf
>,
65 addl_plugins
: Option
<Vec
<String
>>,
66 control
: CompileController
) {
67 macro_rules
! controller_entry_point
{($point
: ident
, $tsess
: expr
, $make_state
: expr
) => ({
68 let state
= $make_state
;
69 (control
.$point
.callback
)(state
);
71 $tsess
.abort_if_errors();
72 if control
.$point
.stop
== Compilation
::Stop
{
77 // We need nested scopes here, because the intermediate results can keep
78 // large chunks of memory alive and we want to free them as soon as
79 // possible to keep the peak memory usage low
81 let (outputs
, expanded_crate
, id
) = {
82 let krate
= phase_1_parse_input(&sess
, cfg
, input
);
84 controller_entry_point
!(after_parse
,
86 CompileState
::state_after_parse(input
, &sess
, outdir
, &krate
));
88 let outputs
= build_output_filenames(input
, outdir
, output
, &krate
.attrs
, &sess
);
89 let id
= link
::find_crate_name(Some(&sess
), &krate
.attrs
, input
);
90 let expanded_crate
= match phase_2_configure_and_expand(&sess
,
99 (outputs
, expanded_crate
, id
)
102 controller_entry_point
!(after_expand
,
104 CompileState
::state_after_expand(input
,
110 let expanded_crate
= assign_node_ids(&sess
, expanded_crate
);
112 let lcx
= LoweringContext
::new(&sess
, Some(&expanded_crate
));
113 let mut hir_forest
= time(sess
.time_passes(),
114 "lowering ast -> hir",
115 || hir_map
::Forest
::new(lower_crate(&lcx
, &expanded_crate
)));
117 // Discard MTWT tables that aren't required past lowering to HIR.
118 if !sess
.opts
.debugging_opts
.keep_mtwt_tables
&&
119 !sess
.opts
.debugging_opts
.save_analysis
{
120 syntax
::ext
::mtwt
::clear_tables();
123 let arenas
= ty
::CtxtArenas
::new();
124 let hir_map
= make_map(&sess
, &mut hir_forest
);
126 write_out_deps(&sess
, &outputs
, &id
);
128 controller_entry_point
!(after_write_deps
,
130 CompileState
::state_after_write_deps(input
,
139 time(sess
.time_passes(), "attribute checking", || {
140 front
::check_attr
::check_crate(&sess
, &expanded_crate
);
143 time(sess
.time_passes(),
145 || lint
::check_ast_crate(&sess
, &expanded_crate
));
147 let opt_crate
= if sess
.opts
.debugging_opts
.keep_ast
||
148 sess
.opts
.debugging_opts
.save_analysis
{
149 Some(&expanded_crate
)
151 drop(expanded_crate
);
155 phase_3_run_analysis_passes(&sess
,
160 control
.make_glob_map
,
161 |tcx
, mir_map
, analysis
| {
165 CompileState
::state_after_analysis(input
,
175 (control
.after_analysis
.callback
)(state
);
177 tcx
.sess
.abort_if_errors();
178 if control
.after_analysis
.stop
== Compilation
::Stop
{
183 if log_enabled
!(::log
::INFO
) {
184 println
!("Pre-trans");
185 tcx
.print_debug_stats();
187 let trans
= phase_4_translate_to_llvm(tcx
,
191 if log_enabled
!(::log
::INFO
) {
192 println
!("Post-trans");
193 tcx
.print_debug_stats();
196 // Discard interned strings as they are no longer required.
197 token
::get_ident_interner().clear();
203 let (outputs
, trans
) = if let Ok(out
) = result
{
209 phase_5_run_llvm_passes(&sess
, &trans
, &outputs
);
211 controller_entry_point
!(after_llvm
,
213 CompileState
::state_after_llvm(input
, &sess
, outdir
, &trans
));
215 phase_6_link_output(&sess
, &trans
, &outputs
);
218 /// The name used for source code that doesn't originate in a file
219 /// (e.g. source from stdin or a string)
220 pub fn anon_src() -> String
{
224 pub fn source_name(input
: &Input
) -> String
{
226 // FIXME (#9639): This needs to handle non-utf8 paths
227 Input
::File(ref ifile
) => ifile
.to_str().unwrap().to_string(),
228 Input
::Str(_
) => anon_src(),
232 /// CompileController is used to customise compilation, it allows compilation to
233 /// be stopped and/or to call arbitrary code at various points in compilation.
234 /// It also allows for various flags to be set to influence what information gets
235 /// collected during compilation.
237 /// This is a somewhat higher level controller than a Session - the Session
238 /// controls what happens in each phase, whereas the CompileController controls
239 /// whether a phase is run at all and whether other code (from outside the
240 /// the compiler) is run between phases.
242 /// Note that if compilation is set to stop and a callback is provided for a
243 /// given entry point, the callback is called before compilation is stopped.
245 /// Expect more entry points to be added in the future.
246 pub struct CompileController
<'a
> {
247 pub after_parse
: PhaseController
<'a
>,
248 pub after_expand
: PhaseController
<'a
>,
249 pub after_write_deps
: PhaseController
<'a
>,
250 pub after_analysis
: PhaseController
<'a
>,
251 pub after_llvm
: PhaseController
<'a
>,
253 pub make_glob_map
: resolve
::MakeGlobMap
,
256 impl<'a
> CompileController
<'a
> {
257 pub fn basic() -> CompileController
<'a
> {
259 after_parse
: PhaseController
::basic(),
260 after_expand
: PhaseController
::basic(),
261 after_write_deps
: PhaseController
::basic(),
262 after_analysis
: PhaseController
::basic(),
263 after_llvm
: PhaseController
::basic(),
264 make_glob_map
: resolve
::MakeGlobMap
::No
,
269 pub struct PhaseController
<'a
> {
270 pub stop
: Compilation
,
271 pub callback
: Box
<Fn(CompileState
) -> () + 'a
>,
274 impl<'a
> PhaseController
<'a
> {
275 pub fn basic() -> PhaseController
<'a
> {
277 stop
: Compilation
::Continue
,
278 callback
: box |_
| {}
,
283 /// State that is passed to a callback. What state is available depends on when
284 /// during compilation the callback is made. See the various constructor methods
285 /// (`state_*`) in the impl to see which data is provided for any given entry point.
286 pub struct CompileState
<'a
, 'ast
: 'a
, 'tcx
: 'a
> {
287 pub input
: &'a Input
,
288 pub session
: &'a Session
,
289 pub cfg
: Option
<&'a ast
::CrateConfig
>,
290 pub krate
: Option
<&'a ast
::Crate
>,
291 pub crate_name
: Option
<&'a
str>,
292 pub output_filenames
: Option
<&'a OutputFilenames
>,
293 pub out_dir
: Option
<&'a Path
>,
294 pub expanded_crate
: Option
<&'a ast
::Crate
>,
295 pub hir_crate
: Option
<&'a hir
::Crate
>,
296 pub ast_map
: Option
<&'a hir_map
::Map
<'ast
>>,
297 pub mir_map
: Option
<&'a MirMap
<'tcx
>>,
298 pub analysis
: Option
<&'a ty
::CrateAnalysis
<'a
>>,
299 pub tcx
: Option
<&'a ty
::ctxt
<'tcx
>>,
300 pub lcx
: Option
<&'a LoweringContext
<'a
>>,
301 pub trans
: Option
<&'a trans
::CrateTranslation
>,
304 impl<'a
, 'ast
, 'tcx
> CompileState
<'a
, 'ast
, 'tcx
> {
305 fn empty(input
: &'a Input
,
306 session
: &'a Session
,
307 out_dir
: &'a Option
<PathBuf
>)
308 -> CompileState
<'a
, 'ast
, 'tcx
> {
312 out_dir
: out_dir
.as_ref().map(|s
| &**s
),
316 output_filenames
: None
,
317 expanded_crate
: None
,
328 fn state_after_parse(input
: &'a Input
,
329 session
: &'a Session
,
330 out_dir
: &'a Option
<PathBuf
>,
331 krate
: &'a ast
::Crate
)
332 -> CompileState
<'a
, 'ast
, 'tcx
> {
333 CompileState { krate: Some(krate), ..CompileState::empty(input, session, out_dir) }
336 fn state_after_expand(input
: &'a Input
,
337 session
: &'a Session
,
338 out_dir
: &'a Option
<PathBuf
>,
339 expanded_crate
: &'a ast
::Crate
,
341 -> CompileState
<'a
, 'ast
, 'tcx
> {
343 crate_name
: Some(crate_name
),
344 expanded_crate
: Some(expanded_crate
),
345 ..CompileState
::empty(input
, session
, out_dir
)
349 fn state_after_write_deps(input
: &'a Input
,
350 session
: &'a Session
,
351 out_dir
: &'a Option
<PathBuf
>,
352 hir_map
: &'a hir_map
::Map
<'ast
>,
353 krate
: &'a ast
::Crate
,
354 hir_crate
: &'a hir
::Crate
,
356 lcx
: &'a LoweringContext
<'a
>)
357 -> CompileState
<'a
, 'ast
, 'tcx
> {
359 crate_name
: Some(crate_name
),
360 ast_map
: Some(hir_map
),
362 hir_crate
: Some(hir_crate
),
364 ..CompileState
::empty(input
, session
, out_dir
)
368 fn state_after_analysis(input
: &'a Input
,
369 session
: &'a Session
,
370 out_dir
: &'a Option
<PathBuf
>,
371 krate
: Option
<&'a ast
::Crate
>,
372 hir_crate
: &'a hir
::Crate
,
373 analysis
: &'a ty
::CrateAnalysis
,
374 mir_map
: &'a MirMap
<'tcx
>,
375 tcx
: &'a ty
::ctxt
<'tcx
>,
376 lcx
: &'a LoweringContext
<'a
>,
378 -> CompileState
<'a
, 'ast
, 'tcx
> {
380 analysis
: Some(analysis
),
381 mir_map
: Some(mir_map
),
384 hir_crate
: Some(hir_crate
),
386 crate_name
: Some(crate_name
),
387 ..CompileState
::empty(input
, session
, out_dir
)
392 fn state_after_llvm(input
: &'a Input
,
393 session
: &'a Session
,
394 out_dir
: &'a Option
<PathBuf
>,
395 trans
: &'a trans
::CrateTranslation
)
396 -> CompileState
<'a
, 'ast
, 'tcx
> {
397 CompileState { trans: Some(trans), ..CompileState::empty(input, session, out_dir) }
401 pub fn phase_1_parse_input(sess
: &Session
, cfg
: ast
::CrateConfig
, input
: &Input
) -> ast
::Crate
{
402 // These may be left in an incoherent state after a previous compile.
403 // `clear_tables` and `get_ident_interner().clear()` can be used to free
404 // memory, but they do not restore the initial state.
405 syntax
::ext
::mtwt
::reset_tables();
406 token
::reset_ident_interner();
408 let krate
= time(sess
.time_passes(), "parsing", || {
410 Input
::File(ref file
) => {
411 parse
::parse_crate_from_file(&(*file
), cfg
.clone(), &sess
.parse_sess
)
413 Input
::Str(ref src
) => {
414 parse
::parse_crate_from_source_str(anon_src().to_string(),
422 if sess
.opts
.debugging_opts
.ast_json_noexpand
{
423 println
!("{}", json
::as_json(&krate
));
426 if sess
.opts
.debugging_opts
.input_stats
{
427 println
!("Lines of code: {}", sess
.codemap().count_lines());
428 println
!("Pre-expansion node count: {}", count_nodes(&krate
));
431 if let Some(ref s
) = sess
.opts
.debugging_opts
.show_span
{
432 syntax
::show_span
::run(sess
.diagnostic(), s
, &krate
);
438 fn count_nodes(krate
: &ast
::Crate
) -> usize {
439 let mut counter
= NodeCounter
::new();
440 visit
::walk_crate(&mut counter
, krate
);
444 // For continuing compilation after a parsed crate has been
447 /// Run the "early phases" of the compiler: initial `cfg` processing,
448 /// loading compiler plugins (including those from `addl_plugins`),
449 /// syntax expansion, secondary `cfg` expansion, synthesis of a test
450 /// harness if one is to be provided and injection of a dependency on the
451 /// standard library and prelude.
453 /// Returns `None` if we're aborting after handling -W help.
454 pub fn phase_2_configure_and_expand(sess
: &Session
,
456 mut krate
: ast
::Crate
,
458 addl_plugins
: Option
<Vec
<String
>>)
459 -> Option
<ast
::Crate
> {
460 let time_passes
= sess
.time_passes();
462 // strip before anything else because crate metadata may use #[cfg_attr]
463 // and so macros can depend on configuration variables, such as
465 // #[macro_use] #[cfg(foo)]
466 // mod bar { macro_rules! baz!(() => {{}}) }
468 // baz! should not use this definition unless foo is enabled.
470 let mut feature_gated_cfgs
= vec
![];
471 krate
= time(time_passes
, "configuration 1", || {
472 syntax
::config
::strip_unconfigured_items(sess
.diagnostic(), krate
, &mut feature_gated_cfgs
)
475 *sess
.crate_types
.borrow_mut() = collect_crate_types(sess
, &krate
.attrs
);
476 *sess
.crate_metadata
.borrow_mut() = collect_crate_metadata(sess
, &krate
.attrs
);
478 time(time_passes
, "recursion limit", || {
479 middle
::recursion_limit
::update_recursion_limit(sess
, &krate
);
482 time(time_passes
, "gated macro checking", || {
483 let features
= syntax
::feature_gate
::check_crate_macros(sess
.codemap(),
484 &sess
.parse_sess
.span_diagnostic
,
487 // these need to be set "early" so that expansion sees `quote` if enabled.
488 *sess
.features
.borrow_mut() = features
;
489 sess
.abort_if_errors();
493 krate
= time(time_passes
, "crate injection", || {
494 syntax
::std_inject
::maybe_inject_crates_ref(krate
, sess
.opts
.alt_std_name
.clone())
497 let macros
= time(time_passes
,
499 || macro_import
::read_macro_defs(sess
, &cstore
, &krate
));
501 let mut addl_plugins
= Some(addl_plugins
);
502 let registrars
= time(time_passes
, "plugin loading", || {
503 plugin
::load
::load_plugins(sess
, &cstore
, &krate
, addl_plugins
.take().unwrap())
506 let mut registry
= Registry
::new(sess
, &krate
);
508 time(time_passes
, "plugin registration", || {
509 if sess
.features
.borrow().rustc_diagnostic_macros
{
510 registry
.register_macro("__diagnostic_used",
511 diagnostics
::plugin
::expand_diagnostic_used
);
512 registry
.register_macro("__register_diagnostic",
513 diagnostics
::plugin
::expand_register_diagnostic
);
514 registry
.register_macro("__build_diagnostic_array",
515 diagnostics
::plugin
::expand_build_diagnostic_array
);
518 for registrar
in registrars
{
519 registry
.args_hidden
= Some(registrar
.args
);
520 (registrar
.fun
)(&mut registry
);
524 let Registry
{ syntax_exts
, early_lint_passes
, late_lint_passes
, lint_groups
,
525 llvm_passes
, attributes
, .. } = registry
;
528 let mut ls
= sess
.lint_store
.borrow_mut();
529 for pass
in early_lint_passes
{
530 ls
.register_early_pass(Some(sess
), true, pass
);
532 for pass
in late_lint_passes
{
533 ls
.register_late_pass(Some(sess
), true, pass
);
536 for (name
, to
) in lint_groups
{
537 ls
.register_group(Some(sess
), true, name
, to
);
540 *sess
.plugin_llvm_passes
.borrow_mut() = llvm_passes
;
541 *sess
.plugin_attributes
.borrow_mut() = attributes
.clone();
544 // Lint plugins are registered; now we can process command line flags.
545 if sess
.opts
.describe_lints
{
546 super::describe_lints(&*sess
.lint_store
.borrow(), true);
549 sess
.lint_store
.borrow_mut().process_command_line(sess
);
551 // Abort if there are errors from lint processing or a plugin registrar.
552 sess
.abort_if_errors();
554 krate
= time(time_passes
, "expansion", || {
555 // Windows dlls do not have rpaths, so they don't know how to find their
556 // dependencies. It's up to us to tell the system where to find all the
557 // dependent dlls. Note that this uses cfg!(windows) as opposed to
558 // targ_cfg because syntax extensions are always loaded for the host
559 // compiler, not for the target.
560 let mut _old_path
= OsString
::new();
562 _old_path
= env
::var_os("PATH").unwrap_or(_old_path
);
563 let mut new_path
= sess
.host_filesearch(PathKind
::All
)
564 .get_dylib_search_paths();
565 new_path
.extend(env
::split_paths(&_old_path
));
566 env
::set_var("PATH", &env
::join_paths(new_path
).unwrap());
568 let features
= sess
.features
.borrow();
569 let cfg
= syntax
::ext
::expand
::ExpansionConfig
{
570 crate_name
: crate_name
.to_string(),
571 features
: Some(&features
),
572 recursion_limit
: sess
.recursion_limit
.get(),
573 trace_mac
: sess
.opts
.debugging_opts
.trace_macros
,
575 let mut ecx
= syntax
::ext
::base
::ExtCtxt
::new(&sess
.parse_sess
,
576 krate
.config
.clone(),
578 &mut feature_gated_cfgs
);
579 syntax_ext
::register_builtins(&mut ecx
.syntax_env
);
580 let (ret
, macro_names
) = syntax
::ext
::expand
::expand_crate(ecx
,
585 env
::set_var("PATH", &_old_path
);
587 *sess
.available_macros
.borrow_mut() = macro_names
;
591 // Needs to go *after* expansion to be able to check the results
592 // of macro expansion. This runs before #[cfg] to try to catch as
593 // much as possible (e.g. help the programmer avoid platform
594 // specific differences)
595 time(time_passes
, "complete gated feature checking 1", || {
596 let features
= syntax
::feature_gate
::check_crate(sess
.codemap(),
597 &sess
.parse_sess
.span_diagnostic
,
600 sess
.opts
.unstable_features
);
601 *sess
.features
.borrow_mut() = features
;
602 sess
.abort_if_errors();
605 // JBC: make CFG processing part of expansion to avoid this problem:
607 // strip again, in case expansion added anything with a #[cfg].
608 krate
= time(time_passes
, "configuration 2", || {
609 syntax
::config
::strip_unconfigured_items(sess
.diagnostic(), krate
, &mut feature_gated_cfgs
)
612 time(time_passes
, "gated configuration checking", || {
613 let features
= sess
.features
.borrow();
614 feature_gated_cfgs
.sort();
615 feature_gated_cfgs
.dedup();
616 for cfg
in &feature_gated_cfgs
{
617 cfg
.check_and_emit(sess
.diagnostic(), &features
, sess
.codemap());
621 krate
= time(time_passes
, "maybe building test harness", || {
622 syntax
::test
::modify_for_testing(&sess
.parse_sess
, &sess
.opts
.cfg
, krate
, sess
.diagnostic())
625 krate
= time(time_passes
,
627 || syntax
::std_inject
::maybe_inject_prelude(&sess
.parse_sess
, krate
));
630 "checking that all macro invocations are gone",
631 || syntax
::ext
::expand
::check_for_macros(&sess
.parse_sess
, &krate
));
634 "checking for inline asm in case the target doesn't support it",
635 || ::rustc_passes
::no_asm
::check_crate(sess
, &krate
));
637 // One final feature gating of the true AST that gets compiled
638 // later, to make sure we've got everything (e.g. configuration
639 // can insert new attributes via `cfg_attr`)
640 time(time_passes
, "complete gated feature checking 2", || {
641 let features
= syntax
::feature_gate
::check_crate(sess
.codemap(),
642 &sess
.parse_sess
.span_diagnostic
,
645 sess
.opts
.unstable_features
);
646 *sess
.features
.borrow_mut() = features
;
647 sess
.abort_if_errors();
651 "const fn bodies and arguments",
652 || ::rustc_passes
::const_fn
::check_crate(sess
, &krate
));
654 if sess
.opts
.debugging_opts
.input_stats
{
655 println
!("Post-expansion node count: {}", count_nodes(&krate
));
661 pub fn assign_node_ids(sess
: &Session
, krate
: ast
::Crate
) -> ast
::Crate
{
662 struct NodeIdAssigner
<'a
> {
666 impl<'a
> Folder
for NodeIdAssigner
<'a
> {
667 fn new_id(&mut self, old_id
: ast
::NodeId
) -> ast
::NodeId
{
668 assert_eq
!(old_id
, ast
::DUMMY_NODE_ID
);
669 self.sess
.next_node_id()
673 let krate
= time(sess
.time_passes(),
674 "assigning node ids",
675 || NodeIdAssigner { sess: sess }
.fold_crate(krate
));
677 if sess
.opts
.debugging_opts
.ast_json
{
678 println
!("{}", json
::as_json(&krate
));
684 pub fn make_map
<'ast
>(sess
: &Session
,
685 forest
: &'ast
mut hir_map
::Forest
)
686 -> hir_map
::Map
<'ast
> {
687 // Construct the HIR map
688 time(sess
.time_passes(),
690 move || hir_map
::map_crate(forest
))
693 /// Run the resolution, typechecking, region checking and other
694 /// miscellaneous analysis passes on the crate. Return various
695 /// structures carrying the results of the analysis.
696 pub fn phase_3_run_analysis_passes
<'tcx
, F
, R
>(sess
: &'tcx Session
,
698 hir_map
: hir_map
::Map
<'tcx
>,
699 arenas
: &'tcx ty
::CtxtArenas
<'tcx
>,
701 make_glob_map
: resolve
::MakeGlobMap
,
704 where F
: for<'a
> FnOnce(&'a ty
::ctxt
<'tcx
>, MirMap
<'tcx
>, ty
::CrateAnalysis
) -> R
706 let time_passes
= sess
.time_passes();
707 let krate
= hir_map
.krate();
710 "external crate/lib resolution",
711 || LocalCrateReader
::new(sess
, cstore
, &hir_map
).read_crates(krate
));
713 let lang_items
= time(time_passes
,
714 "language item collection",
715 || middle
::lang_items
::collect_language_items(&sess
, &hir_map
));
717 let resolve
::CrateMap
{
724 } = time(time_passes
,
726 || resolve
::resolve_crate(sess
, &hir_map
, make_glob_map
));
728 let named_region_map
= time(time_passes
,
729 "lifetime resolution",
730 || middle
::resolve_lifetime
::krate(sess
, krate
, &def_map
.borrow()));
733 "looking for entry point",
734 || middle
::entry
::find_entry_point(sess
, &hir_map
));
736 sess
.plugin_registrar_fn
.set(time(time_passes
, "looking for plugin registrar", || {
737 plugin
::build
::find_plugin_registrar(sess
.diagnostic(), krate
)
740 let region_map
= time(time_passes
,
742 || middle
::region
::resolve_crate(sess
, krate
));
746 || middle
::check_loop
::check_crate(sess
, krate
));
749 "static item recursion checking",
750 || middle
::check_static_recursion
::check_crate(sess
, krate
, &def_map
.borrow(), &hir_map
));
752 ty
::ctxt
::create_and_enter(sess
,
760 stability
::Index
::new(krate
),
762 // passes are timed inside typeck
763 typeck
::check_crate(tcx
, trait_map
);
767 || middle
::check_const
::check_crate(tcx
));
770 time(time_passes
, "privacy checking", || {
771 rustc_privacy
::check_crate(tcx
,
776 // Do not move this check past lint
777 time(time_passes
, "stability index", || {
778 tcx
.stability
.borrow_mut().build(tcx
, krate
, &access_levels
)
782 "intrinsic checking",
783 || middle
::intrinsicck
::check_crate(tcx
));
787 || middle
::effect
::check_crate(tcx
));
791 || middle
::check_match
::check_crate(tcx
));
796 || mir
::mir_map
::build_mir_for_crate(tcx
));
800 || middle
::liveness
::check_crate(tcx
));
804 || borrowck
::check_crate(tcx
));
808 || middle
::check_rvalues
::check_crate(tcx
));
810 // Avoid overwhelming user with errors if type checking failed.
811 // I'm not sure how helpful this is, to be honest, but it avoids
813 // lot of annoying errors in the compile-fail tests (basically,
814 // lint warnings and so on -- kindck used to do this abort, but
815 // kindck is gone now). -nmatsakis
816 tcx
.sess
.abort_if_errors();
820 "reachability checking",
821 || reachable
::find_reachable(tcx
, &access_levels
));
823 time(time_passes
, "death checking", || {
824 middle
::dead
::check_crate(tcx
, &access_levels
);
827 let ref lib_features_used
=
829 "stability checking",
830 || stability
::check_unstable_api_usage(tcx
));
832 time(time_passes
, "unused lib feature checking", || {
833 stability
::check_unused_or_stable_features(&tcx
.sess
,
839 || lint
::check_crate(tcx
, &access_levels
));
841 // The above three passes generate errors w/o aborting
842 tcx
.sess
.abort_if_errors();
847 export_map
: export_map
,
848 access_levels
: access_levels
,
849 reachable
: reachable_map
,
856 /// Run the translation phase to LLVM, after which the AST and analysis can
858 pub fn phase_4_translate_to_llvm
<'tcx
>(tcx
: &ty
::ctxt
<'tcx
>,
859 mut mir_map
: MirMap
<'tcx
>,
860 analysis
: ty
::CrateAnalysis
)
861 -> trans
::CrateTranslation
{
862 let time_passes
= tcx
.sess
.time_passes();
865 "resolving dependency formats",
866 || dependency_format
::calculate(&tcx
.sess
));
869 "erasing regions from MIR",
870 || mir
::transform
::erase_regions
::erase_regions(tcx
, &mut mir_map
));
872 // Option dance to work around the lack of stack once closures.
875 move || trans
::trans_crate(tcx
, &mir_map
, analysis
))
878 /// Run LLVM itself, producing a bitcode file, assembly file or object file
879 /// as a side effect.
880 pub fn phase_5_run_llvm_passes(sess
: &Session
,
881 trans
: &trans
::CrateTranslation
,
882 outputs
: &OutputFilenames
) {
883 if sess
.opts
.cg
.no_integrated_as
{
884 let mut map
= HashMap
::new();
885 map
.insert(OutputType
::Assembly
, None
);
886 time(sess
.time_passes(),
888 || write
::run_passes(sess
, trans
, &map
, outputs
));
890 write
::run_assembler(sess
, outputs
);
892 // Remove assembly source, unless --save-temps was specified
893 if !sess
.opts
.cg
.save_temps
{
894 fs
::remove_file(&outputs
.temp_path(OutputType
::Assembly
)).unwrap();
897 time(sess
.time_passes(),
899 || write
::run_passes(sess
, trans
, &sess
.opts
.output_types
, outputs
));
902 sess
.abort_if_errors();
905 /// Run the linker on any artifacts that resulted from the LLVM run.
906 /// This should produce either a finished executable or library.
907 pub fn phase_6_link_output(sess
: &Session
,
908 trans
: &trans
::CrateTranslation
,
909 outputs
: &OutputFilenames
) {
910 time(sess
.time_passes(),
912 || link
::link_binary(sess
, trans
, outputs
, &trans
.link
.crate_name
));
915 fn escape_dep_filename(filename
: &str) -> String
{
916 // Apparently clang and gcc *only* escape spaces:
917 // http://llvm.org/klaus/clang/commit/9d50634cfc268ecc9a7250226dd5ca0e945240d4
918 filename
.replace(" ", "\\ ")
921 fn write_out_deps(sess
: &Session
, outputs
: &OutputFilenames
, id
: &str) {
922 let mut out_filenames
= Vec
::new();
923 for output_type
in sess
.opts
.output_types
.keys() {
924 let file
= outputs
.path(*output_type
);
927 for output
in sess
.crate_types
.borrow().iter() {
928 let p
= link
::filename_for_input(sess
, *output
, id
, outputs
);
929 out_filenames
.push(p
);
933 out_filenames
.push(file
);
938 // Write out dependency rules to the dep-info file if requested
939 if !sess
.opts
.output_types
.contains_key(&OutputType
::DepInfo
) {
942 let deps_filename
= outputs
.path(OutputType
::DepInfo
);
945 (|| -> io
::Result
<()> {
946 // Build a list of files used to compile the output and
947 // write Makefile-compatible dependency rules
948 let files
: Vec
<String
> = sess
.codemap()
952 .filter(|fmap
| fmap
.is_real_file())
953 .filter(|fmap
| !fmap
.is_imported())
954 .map(|fmap
| escape_dep_filename(&fmap
.name
))
956 let mut file
= try
!(fs
::File
::create(&deps_filename
));
957 for path
in &out_filenames
{
958 try
!(write
!(file
, "{}: {}\n\n", path
.display(), files
.join(" ")));
961 // Emit a fake target for each input file to the compilation. This
962 // prevents `make` from spitting out an error if a file is later
963 // deleted. For more info see #28735
965 try
!(writeln
!(file
, "{}:", path
));
973 sess
.fatal(&format
!("error writing dependencies to `{}`: {}",
974 deps_filename
.display(),
980 pub fn collect_crate_types(session
: &Session
, attrs
: &[ast
::Attribute
]) -> Vec
<config
::CrateType
> {
981 // Unconditionally collect crate types from attributes to make them used
982 let attr_types
: Vec
<config
::CrateType
> =
985 if a
.check_name("crate_type") {
986 match a
.value_str() {
987 Some(ref n
) if *n
== "rlib" => {
988 Some(config
::CrateTypeRlib
)
990 Some(ref n
) if *n
== "dylib" => {
991 Some(config
::CrateTypeDylib
)
993 Some(ref n
) if *n
== "lib" => {
994 Some(config
::default_lib_output())
996 Some(ref n
) if *n
== "staticlib" => {
997 Some(config
::CrateTypeStaticlib
)
999 Some(ref n
) if *n
== "bin" => Some(config
::CrateTypeExecutable
),
1001 session
.add_lint(lint
::builtin
::UNKNOWN_CRATE_TYPES
,
1004 "invalid `crate_type` value".to_string());
1008 session
.struct_span_err(a
.span
, "`crate_type` requires a value")
1009 .note("for example: `#![crate_type=\"lib\"]`")
1020 // If we're generating a test executable, then ignore all other output
1021 // styles at all other locations
1022 if session
.opts
.test
{
1023 return vec
![config
::CrateTypeExecutable
];
1026 // Only check command line flags if present. If no types are specified by
1027 // command line, then reuse the empty `base` Vec to hold the types that
1028 // will be found in crate attributes.
1029 let mut base
= session
.opts
.crate_types
.clone();
1030 if base
.is_empty() {
1031 base
.extend(attr_types
);
1032 if base
.is_empty() {
1033 base
.push(link
::default_output_for_target(session
));
1040 .filter(|crate_type
| {
1041 let res
= !link
::invalid_output_for_target(session
, *crate_type
);
1044 session
.warn(&format
!("dropping unsupported crate type `{}` for target `{}`",
1046 session
.opts
.target_triple
));
1054 pub fn collect_crate_metadata(session
: &Session
, _attrs
: &[ast
::Attribute
]) -> Vec
<String
> {
1055 session
.opts
.cg
.metadata
.clone()
1058 pub fn build_output_filenames(input
: &Input
,
1059 odir
: &Option
<PathBuf
>,
1060 ofile
: &Option
<PathBuf
>,
1061 attrs
: &[ast
::Attribute
],
1063 -> OutputFilenames
{
1066 // "-" as input file will cause the parser to read from stdin so we
1067 // have to make up a name
1068 // We want to toss everything after the final '.'
1069 let dirpath
= match *odir
{
1070 Some(ref d
) => d
.clone(),
1071 None
=> PathBuf
::new(),
1074 // If a crate name is present, we use it as the link name
1075 let stem
= sess
.opts
1078 .or_else(|| attr
::find_crate_name(attrs
).map(|n
| n
.to_string()))
1079 .unwrap_or(input
.filestem());
1082 out_directory
: dirpath
,
1084 single_output_file
: None
,
1085 extra
: sess
.opts
.cg
.extra_filename
.clone(),
1086 outputs
: sess
.opts
.output_types
.clone(),
1090 Some(ref out_file
) => {
1091 let unnamed_output_types
= sess
.opts
1094 .filter(|a
| a
.is_none())
1096 let ofile
= if unnamed_output_types
> 1 {
1097 sess
.warn("ignoring specified output filename because multiple outputs were \
1101 Some(out_file
.clone())
1104 sess
.warn("ignoring --out-dir flag due to -o flag.");
1107 let cur_dir
= Path
::new("");
1110 out_directory
: out_file
.parent().unwrap_or(cur_dir
).to_path_buf(),
1111 out_filestem
: out_file
.file_stem()
1112 .unwrap_or(OsStr
::new(""))
1116 single_output_file
: ofile
,
1117 extra
: sess
.opts
.cg
.extra_filename
.clone(),
1118 outputs
: sess
.opts
.output_types
.clone(),