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
;
58 pub fn compile_input(sess
: Session
,
60 cfg
: ast
::CrateConfig
,
62 outdir
: &Option
<PathBuf
>,
63 output
: &Option
<PathBuf
>,
64 addl_plugins
: Option
<Vec
<String
>>,
65 control
: CompileController
) {
66 macro_rules
! controller_entry_point
{($point
: ident
, $tsess
: expr
, $make_state
: expr
) => ({
67 let state
= $make_state
;
68 (control
.$point
.callback
)(state
);
70 $tsess
.abort_if_errors();
71 if control
.$point
.stop
== Compilation
::Stop
{
76 // We need nested scopes here, because the intermediate results can keep
77 // large chunks of memory alive and we want to free them as soon as
78 // possible to keep the peak memory usage low
80 let (outputs
, expanded_crate
, id
) = {
81 let krate
= phase_1_parse_input(&sess
, cfg
, input
);
83 controller_entry_point
!(after_parse
,
85 CompileState
::state_after_parse(input
, &sess
, outdir
, &krate
));
87 let outputs
= build_output_filenames(input
, outdir
, output
, &krate
.attrs
, &sess
);
88 let id
= link
::find_crate_name(Some(&sess
), &krate
.attrs
, input
);
89 let expanded_crate
= match phase_2_configure_and_expand(&sess
,
98 (outputs
, expanded_crate
, id
)
101 controller_entry_point
!(after_expand
,
103 CompileState
::state_after_expand(input
,
109 let expanded_crate
= assign_node_ids(&sess
, expanded_crate
);
111 let lcx
= LoweringContext
::new(&sess
, Some(&expanded_crate
));
112 let mut hir_forest
= time(sess
.time_passes(),
113 "lowering ast -> hir",
114 || hir_map
::Forest
::new(lower_crate(&lcx
, &expanded_crate
)));
116 // Discard MTWT tables that aren't required past lowering to HIR.
117 if !sess
.opts
.debugging_opts
.keep_mtwt_tables
&&
118 !sess
.opts
.debugging_opts
.save_analysis
{
119 syntax
::ext
::mtwt
::clear_tables();
122 let arenas
= ty
::CtxtArenas
::new();
123 let ast_map
= make_map(&sess
, &mut hir_forest
);
125 write_out_deps(&sess
, &outputs
, &id
);
127 controller_entry_point
!(after_write_deps
,
129 CompileState
::state_after_write_deps(input
,
138 time(sess
.time_passes(), "attribute checking", || {
139 front
::check_attr
::check_crate(&sess
, &expanded_crate
);
142 time(sess
.time_passes(),
144 || lint
::check_ast_crate(&sess
, &expanded_crate
));
146 phase_3_run_analysis_passes(&sess
,
151 control
.make_glob_map
,
152 |tcx
, mir_map
, analysis
| {
156 CompileState
::state_after_analysis(input
,
166 (control
.after_analysis
.callback
)(state
);
168 tcx
.sess
.abort_if_errors();
169 if control
.after_analysis
.stop
== Compilation
::Stop
{
174 if log_enabled
!(::log
::INFO
) {
175 println
!("Pre-trans");
176 tcx
.print_debug_stats();
178 let trans
= phase_4_translate_to_llvm(tcx
,
182 if log_enabled
!(::log
::INFO
) {
183 println
!("Post-trans");
184 tcx
.print_debug_stats();
187 // Discard interned strings as they are no longer required.
188 token
::get_ident_interner().clear();
194 let (outputs
, trans
) = if let Ok(out
) = result
{
200 phase_5_run_llvm_passes(&sess
, &trans
, &outputs
);
202 controller_entry_point
!(after_llvm
,
204 CompileState
::state_after_llvm(input
, &sess
, outdir
, &trans
));
206 phase_6_link_output(&sess
, &trans
, &outputs
);
209 /// The name used for source code that doesn't originate in a file
210 /// (e.g. source from stdin or a string)
211 pub fn anon_src() -> String
{
215 pub fn source_name(input
: &Input
) -> String
{
217 // FIXME (#9639): This needs to handle non-utf8 paths
218 Input
::File(ref ifile
) => ifile
.to_str().unwrap().to_string(),
219 Input
::Str(_
) => anon_src(),
223 /// CompileController is used to customise compilation, it allows compilation to
224 /// be stopped and/or to call arbitrary code at various points in compilation.
225 /// It also allows for various flags to be set to influence what information gets
226 /// collected during compilation.
228 /// This is a somewhat higher level controller than a Session - the Session
229 /// controls what happens in each phase, whereas the CompileController controls
230 /// whether a phase is run at all and whether other code (from outside the
231 /// the compiler) is run between phases.
233 /// Note that if compilation is set to stop and a callback is provided for a
234 /// given entry point, the callback is called before compilation is stopped.
236 /// Expect more entry points to be added in the future.
237 pub struct CompileController
<'a
> {
238 pub after_parse
: PhaseController
<'a
>,
239 pub after_expand
: PhaseController
<'a
>,
240 pub after_write_deps
: PhaseController
<'a
>,
241 pub after_analysis
: PhaseController
<'a
>,
242 pub after_llvm
: PhaseController
<'a
>,
244 pub make_glob_map
: resolve
::MakeGlobMap
,
247 impl<'a
> CompileController
<'a
> {
248 pub fn basic() -> CompileController
<'a
> {
250 after_parse
: PhaseController
::basic(),
251 after_expand
: PhaseController
::basic(),
252 after_write_deps
: PhaseController
::basic(),
253 after_analysis
: PhaseController
::basic(),
254 after_llvm
: PhaseController
::basic(),
255 make_glob_map
: resolve
::MakeGlobMap
::No
,
260 pub struct PhaseController
<'a
> {
261 pub stop
: Compilation
,
262 pub callback
: Box
<Fn(CompileState
) -> () + 'a
>,
265 impl<'a
> PhaseController
<'a
> {
266 pub fn basic() -> PhaseController
<'a
> {
268 stop
: Compilation
::Continue
,
269 callback
: box |_
| {}
,
274 /// State that is passed to a callback. What state is available depends on when
275 /// during compilation the callback is made. See the various constructor methods
276 /// (`state_*`) in the impl to see which data is provided for any given entry point.
277 pub struct CompileState
<'a
, 'ast
: 'a
, 'tcx
: 'a
> {
278 pub input
: &'a Input
,
279 pub session
: &'a Session
,
280 pub cfg
: Option
<&'a ast
::CrateConfig
>,
281 pub krate
: Option
<&'a ast
::Crate
>,
282 pub crate_name
: Option
<&'a
str>,
283 pub output_filenames
: Option
<&'a OutputFilenames
>,
284 pub out_dir
: Option
<&'a Path
>,
285 pub expanded_crate
: Option
<&'a ast
::Crate
>,
286 pub hir_crate
: Option
<&'a hir
::Crate
>,
287 pub ast_map
: Option
<&'a hir_map
::Map
<'ast
>>,
288 pub mir_map
: Option
<&'a MirMap
<'tcx
>>,
289 pub analysis
: Option
<&'a ty
::CrateAnalysis
<'a
>>,
290 pub tcx
: Option
<&'a ty
::ctxt
<'tcx
>>,
291 pub lcx
: Option
<&'a LoweringContext
<'a
>>,
292 pub trans
: Option
<&'a trans
::CrateTranslation
>,
295 impl<'a
, 'ast
, 'tcx
> CompileState
<'a
, 'ast
, 'tcx
> {
296 fn empty(input
: &'a Input
,
297 session
: &'a Session
,
298 out_dir
: &'a Option
<PathBuf
>)
299 -> CompileState
<'a
, 'ast
, 'tcx
> {
303 out_dir
: out_dir
.as_ref().map(|s
| &**s
),
307 output_filenames
: None
,
308 expanded_crate
: None
,
319 fn state_after_parse(input
: &'a Input
,
320 session
: &'a Session
,
321 out_dir
: &'a Option
<PathBuf
>,
322 krate
: &'a ast
::Crate
)
323 -> CompileState
<'a
, 'ast
, 'tcx
> {
324 CompileState { krate: Some(krate), ..CompileState::empty(input, session, out_dir) }
327 fn state_after_expand(input
: &'a Input
,
328 session
: &'a Session
,
329 out_dir
: &'a Option
<PathBuf
>,
330 expanded_crate
: &'a ast
::Crate
,
332 -> CompileState
<'a
, 'ast
, 'tcx
> {
334 crate_name
: Some(crate_name
),
335 expanded_crate
: Some(expanded_crate
),
336 ..CompileState
::empty(input
, session
, out_dir
)
340 fn state_after_write_deps(input
: &'a Input
,
341 session
: &'a Session
,
342 out_dir
: &'a Option
<PathBuf
>,
343 ast_map
: &'a hir_map
::Map
<'ast
>,
344 krate
: &'a ast
::Crate
,
345 hir_crate
: &'a hir
::Crate
,
347 lcx
: &'a LoweringContext
<'a
>)
348 -> CompileState
<'a
, 'ast
, 'tcx
> {
350 crate_name
: Some(crate_name
),
351 ast_map
: Some(ast_map
),
353 hir_crate
: Some(hir_crate
),
355 ..CompileState
::empty(input
, session
, out_dir
)
359 fn state_after_analysis(input
: &'a Input
,
360 session
: &'a Session
,
361 out_dir
: &'a Option
<PathBuf
>,
362 krate
: &'a ast
::Crate
,
363 hir_crate
: &'a hir
::Crate
,
364 analysis
: &'a ty
::CrateAnalysis
,
365 mir_map
: &'a MirMap
<'tcx
>,
366 tcx
: &'a ty
::ctxt
<'tcx
>,
367 lcx
: &'a LoweringContext
<'a
>,
369 -> CompileState
<'a
, 'ast
, 'tcx
> {
371 analysis
: Some(analysis
),
372 mir_map
: Some(mir_map
),
375 hir_crate
: Some(hir_crate
),
377 crate_name
: Some(crate_name
),
378 ..CompileState
::empty(input
, session
, out_dir
)
383 fn state_after_llvm(input
: &'a Input
,
384 session
: &'a Session
,
385 out_dir
: &'a Option
<PathBuf
>,
386 trans
: &'a trans
::CrateTranslation
)
387 -> CompileState
<'a
, 'ast
, 'tcx
> {
388 CompileState { trans: Some(trans), ..CompileState::empty(input, session, out_dir) }
392 pub fn phase_1_parse_input(sess
: &Session
, cfg
: ast
::CrateConfig
, input
: &Input
) -> ast
::Crate
{
393 // These may be left in an incoherent state after a previous compile.
394 // `clear_tables` and `get_ident_interner().clear()` can be used to free
395 // memory, but they do not restore the initial state.
396 syntax
::ext
::mtwt
::reset_tables();
397 token
::reset_ident_interner();
399 let krate
= time(sess
.time_passes(), "parsing", || {
401 Input
::File(ref file
) => {
402 parse
::parse_crate_from_file(&(*file
), cfg
.clone(), &sess
.parse_sess
)
404 Input
::Str(ref src
) => {
405 parse
::parse_crate_from_source_str(anon_src().to_string(),
413 if sess
.opts
.debugging_opts
.ast_json_noexpand
{
414 println
!("{}", json
::as_json(&krate
));
417 if sess
.opts
.debugging_opts
.input_stats
{
418 println
!("Lines of code: {}", sess
.codemap().count_lines());
419 println
!("Pre-expansion node count: {}", count_nodes(&krate
));
422 if let Some(ref s
) = sess
.opts
.show_span
{
423 syntax
::show_span
::run(sess
.diagnostic(), s
, &krate
);
429 fn count_nodes(krate
: &ast
::Crate
) -> usize {
430 let mut counter
= NodeCounter
::new();
431 visit
::walk_crate(&mut counter
, krate
);
435 // For continuing compilation after a parsed crate has been
438 /// Run the "early phases" of the compiler: initial `cfg` processing,
439 /// loading compiler plugins (including those from `addl_plugins`),
440 /// syntax expansion, secondary `cfg` expansion, synthesis of a test
441 /// harness if one is to be provided and injection of a dependency on the
442 /// standard library and prelude.
444 /// Returns `None` if we're aborting after handling -W help.
445 pub fn phase_2_configure_and_expand(sess
: &Session
,
447 mut krate
: ast
::Crate
,
449 addl_plugins
: Option
<Vec
<String
>>)
450 -> Option
<ast
::Crate
> {
451 let time_passes
= sess
.time_passes();
453 // strip before anything else because crate metadata may use #[cfg_attr]
454 // and so macros can depend on configuration variables, such as
456 // #[macro_use] #[cfg(foo)]
457 // mod bar { macro_rules! baz!(() => {{}}) }
459 // baz! should not use this definition unless foo is enabled.
461 let mut feature_gated_cfgs
= vec
![];
462 krate
= time(time_passes
, "configuration 1", || {
463 syntax
::config
::strip_unconfigured_items(sess
.diagnostic(), krate
, &mut feature_gated_cfgs
)
466 *sess
.crate_types
.borrow_mut() = collect_crate_types(sess
, &krate
.attrs
);
467 *sess
.crate_metadata
.borrow_mut() = collect_crate_metadata(sess
, &krate
.attrs
);
469 time(time_passes
, "recursion limit", || {
470 middle
::recursion_limit
::update_recursion_limit(sess
, &krate
);
473 time(time_passes
, "gated macro checking", || {
474 let features
= syntax
::feature_gate
::check_crate_macros(sess
.codemap(),
475 &sess
.parse_sess
.span_diagnostic
,
478 // these need to be set "early" so that expansion sees `quote` if enabled.
479 *sess
.features
.borrow_mut() = features
;
480 sess
.abort_if_errors();
484 krate
= time(time_passes
, "crate injection", || {
485 syntax
::std_inject
::maybe_inject_crates_ref(krate
, sess
.opts
.alt_std_name
.clone())
488 let macros
= time(time_passes
,
490 || macro_import
::read_macro_defs(sess
, &cstore
, &krate
));
492 let mut addl_plugins
= Some(addl_plugins
);
493 let registrars
= time(time_passes
, "plugin loading", || {
494 plugin
::load
::load_plugins(sess
, &cstore
, &krate
, addl_plugins
.take().unwrap())
497 let mut registry
= Registry
::new(sess
, &krate
);
499 time(time_passes
, "plugin registration", || {
500 if sess
.features
.borrow().rustc_diagnostic_macros
{
501 registry
.register_macro("__diagnostic_used",
502 diagnostics
::plugin
::expand_diagnostic_used
);
503 registry
.register_macro("__register_diagnostic",
504 diagnostics
::plugin
::expand_register_diagnostic
);
505 registry
.register_macro("__build_diagnostic_array",
506 diagnostics
::plugin
::expand_build_diagnostic_array
);
509 for registrar
in registrars
{
510 registry
.args_hidden
= Some(registrar
.args
);
511 (registrar
.fun
)(&mut registry
);
515 let Registry
{ syntax_exts
, early_lint_passes
, late_lint_passes
, lint_groups
,
516 llvm_passes
, attributes
, .. } = registry
;
519 let mut ls
= sess
.lint_store
.borrow_mut();
520 for pass
in early_lint_passes
{
521 ls
.register_early_pass(Some(sess
), true, pass
);
523 for pass
in late_lint_passes
{
524 ls
.register_late_pass(Some(sess
), true, pass
);
527 for (name
, to
) in lint_groups
{
528 ls
.register_group(Some(sess
), true, name
, to
);
531 *sess
.plugin_llvm_passes
.borrow_mut() = llvm_passes
;
532 *sess
.plugin_attributes
.borrow_mut() = attributes
.clone();
535 // Lint plugins are registered; now we can process command line flags.
536 if sess
.opts
.describe_lints
{
537 super::describe_lints(&*sess
.lint_store
.borrow(), true);
540 sess
.lint_store
.borrow_mut().process_command_line(sess
);
542 // Abort if there are errors from lint processing or a plugin registrar.
543 sess
.abort_if_errors();
545 krate
= time(time_passes
, "expansion", || {
546 // Windows dlls do not have rpaths, so they don't know how to find their
547 // dependencies. It's up to us to tell the system where to find all the
548 // dependent dlls. Note that this uses cfg!(windows) as opposed to
549 // targ_cfg because syntax extensions are always loaded for the host
550 // compiler, not for the target.
551 let mut _old_path
= OsString
::new();
553 _old_path
= env
::var_os("PATH").unwrap_or(_old_path
);
554 let mut new_path
= sess
.host_filesearch(PathKind
::All
)
555 .get_dylib_search_paths();
556 new_path
.extend(env
::split_paths(&_old_path
));
557 env
::set_var("PATH", &env
::join_paths(new_path
).unwrap());
559 let features
= sess
.features
.borrow();
560 let cfg
= syntax
::ext
::expand
::ExpansionConfig
{
561 crate_name
: crate_name
.to_string(),
562 features
: Some(&features
),
563 recursion_limit
: sess
.recursion_limit
.get(),
564 trace_mac
: sess
.opts
.debugging_opts
.trace_macros
,
566 let (ret
, macro_names
) = syntax
::ext
::expand
::expand_crate(&sess
.parse_sess
,
570 &mut feature_gated_cfgs
,
573 env
::set_var("PATH", &_old_path
);
575 *sess
.available_macros
.borrow_mut() = macro_names
;
579 // Needs to go *after* expansion to be able to check the results
580 // of macro expansion. This runs before #[cfg] to try to catch as
581 // much as possible (e.g. help the programmer avoid platform
582 // specific differences)
583 time(time_passes
, "complete gated feature checking 1", || {
584 let features
= syntax
::feature_gate
::check_crate(sess
.codemap(),
585 &sess
.parse_sess
.span_diagnostic
,
588 sess
.opts
.unstable_features
);
589 *sess
.features
.borrow_mut() = features
;
590 sess
.abort_if_errors();
593 // JBC: make CFG processing part of expansion to avoid this problem:
595 // strip again, in case expansion added anything with a #[cfg].
596 krate
= time(time_passes
, "configuration 2", || {
597 syntax
::config
::strip_unconfigured_items(sess
.diagnostic(), krate
, &mut feature_gated_cfgs
)
600 time(time_passes
, "gated configuration checking", || {
601 let features
= sess
.features
.borrow();
602 feature_gated_cfgs
.sort();
603 feature_gated_cfgs
.dedup();
604 for cfg
in &feature_gated_cfgs
{
605 cfg
.check_and_emit(sess
.diagnostic(), &features
);
609 krate
= time(time_passes
, "maybe building test harness", || {
610 syntax
::test
::modify_for_testing(&sess
.parse_sess
, &sess
.opts
.cfg
, krate
, sess
.diagnostic())
613 krate
= time(time_passes
,
615 || syntax
::std_inject
::maybe_inject_prelude(&sess
.parse_sess
, krate
));
618 "checking that all macro invocations are gone",
619 || syntax
::ext
::expand
::check_for_macros(&sess
.parse_sess
, &krate
));
622 "checking for inline asm in case the target doesn't support it",
623 || middle
::check_no_asm
::check_crate(sess
, &krate
));
625 // One final feature gating of the true AST that gets compiled
626 // later, to make sure we've got everything (e.g. configuration
627 // can insert new attributes via `cfg_attr`)
628 time(time_passes
, "complete gated feature checking 2", || {
629 let features
= syntax
::feature_gate
::check_crate(sess
.codemap(),
630 &sess
.parse_sess
.span_diagnostic
,
633 sess
.opts
.unstable_features
);
634 *sess
.features
.borrow_mut() = features
;
635 sess
.abort_if_errors();
638 if sess
.opts
.debugging_opts
.input_stats
{
639 println
!("Post-expansion node count: {}", count_nodes(&krate
));
645 pub fn assign_node_ids(sess
: &Session
, krate
: ast
::Crate
) -> ast
::Crate
{
646 struct NodeIdAssigner
<'a
> {
650 impl<'a
> Folder
for NodeIdAssigner
<'a
> {
651 fn new_id(&mut self, old_id
: ast
::NodeId
) -> ast
::NodeId
{
652 assert_eq
!(old_id
, ast
::DUMMY_NODE_ID
);
653 self.sess
.next_node_id()
657 let krate
= time(sess
.time_passes(),
658 "assigning node ids",
659 || NodeIdAssigner { sess: sess }
.fold_crate(krate
));
661 if sess
.opts
.debugging_opts
.ast_json
{
662 println
!("{}", json
::as_json(&krate
));
668 pub fn make_map
<'ast
>(sess
: &Session
,
669 forest
: &'ast
mut front
::map
::Forest
)
670 -> front
::map
::Map
<'ast
> {
671 // Construct the 'ast'-map
672 let map
= time(sess
.time_passes(),
674 move || front
::map
::map_crate(forest
));
679 /// Run the resolution, typechecking, region checking and other
680 /// miscellaneous analysis passes on the crate. Return various
681 /// structures carrying the results of the analysis.
682 pub fn phase_3_run_analysis_passes
<'tcx
, F
, R
>(sess
: &'tcx Session
,
684 ast_map
: front
::map
::Map
<'tcx
>,
685 arenas
: &'tcx ty
::CtxtArenas
<'tcx
>,
687 make_glob_map
: resolve
::MakeGlobMap
,
690 where F
: for<'a
> FnOnce(&'a ty
::ctxt
<'tcx
>, MirMap
<'tcx
>, ty
::CrateAnalysis
) -> R
692 let time_passes
= sess
.time_passes();
693 let krate
= ast_map
.krate();
696 "external crate/lib resolution",
697 || LocalCrateReader
::new(sess
, cstore
, &ast_map
).read_crates(krate
));
699 let lang_items
= time(time_passes
,
700 "language item collection",
701 || middle
::lang_items
::collect_language_items(&sess
, &ast_map
));
703 let resolve
::CrateMap
{
710 } = time(time_passes
,
712 || resolve
::resolve_crate(sess
, &ast_map
, make_glob_map
));
714 let named_region_map
= time(time_passes
,
715 "lifetime resolution",
716 || middle
::resolve_lifetime
::krate(sess
, krate
, &def_map
.borrow()));
719 "looking for entry point",
720 || middle
::entry
::find_entry_point(sess
, &ast_map
));
722 sess
.plugin_registrar_fn
.set(time(time_passes
, "looking for plugin registrar", || {
723 plugin
::build
::find_plugin_registrar(sess
.diagnostic(), krate
)
726 let region_map
= time(time_passes
,
728 || middle
::region
::resolve_crate(sess
, krate
));
732 || middle
::check_loop
::check_crate(sess
, krate
));
735 "static item recursion checking",
736 || middle
::check_static_recursion
::check_crate(sess
, krate
, &def_map
.borrow(), &ast_map
));
738 ty
::ctxt
::create_and_enter(sess
,
746 stability
::Index
::new(krate
),
748 // passes are timed inside typeck
749 typeck
::check_crate(tcx
, trait_map
);
753 || middle
::check_const
::check_crate(tcx
));
756 time(time_passes
, "privacy checking", || {
757 rustc_privacy
::check_crate(tcx
,
762 // Do not move this check past lint
763 time(time_passes
, "stability index", || {
764 tcx
.stability
.borrow_mut().build(tcx
, krate
, &access_levels
)
768 "intrinsic checking",
769 || middle
::intrinsicck
::check_crate(tcx
));
773 || middle
::effect
::check_crate(tcx
));
777 || middle
::check_match
::check_crate(tcx
));
782 || mir
::mir_map
::build_mir_for_crate(tcx
));
786 || middle
::liveness
::check_crate(tcx
));
790 || borrowck
::check_crate(tcx
));
794 || middle
::check_rvalues
::check_crate(tcx
, krate
));
796 // Avoid overwhelming user with errors if type checking failed.
797 // I'm not sure how helpful this is, to be honest, but it avoids
799 // lot of annoying errors in the compile-fail tests (basically,
800 // lint warnings and so on -- kindck used to do this abort, but
801 // kindck is gone now). -nmatsakis
802 tcx
.sess
.abort_if_errors();
806 "reachability checking",
807 || reachable
::find_reachable(tcx
, &access_levels
));
809 time(time_passes
, "death checking", || {
810 middle
::dead
::check_crate(tcx
, &access_levels
);
813 let ref lib_features_used
=
815 "stability checking",
816 || stability
::check_unstable_api_usage(tcx
));
818 time(time_passes
, "unused lib feature checking", || {
819 stability
::check_unused_or_stable_features(&tcx
.sess
,
825 || lint
::check_crate(tcx
, &access_levels
));
827 // The above three passes generate errors w/o aborting
828 tcx
.sess
.abort_if_errors();
833 export_map
: export_map
,
834 access_levels
: access_levels
,
835 reachable
: reachable_map
,
842 /// Run the translation phase to LLVM, after which the AST and analysis can
844 pub fn phase_4_translate_to_llvm
<'tcx
>(tcx
: &ty
::ctxt
<'tcx
>,
845 mut mir_map
: MirMap
<'tcx
>,
846 analysis
: ty
::CrateAnalysis
)
847 -> trans
::CrateTranslation
{
848 let time_passes
= tcx
.sess
.time_passes();
851 "resolving dependency formats",
852 || dependency_format
::calculate(&tcx
.sess
));
855 "erasing regions from MIR",
856 || mir
::transform
::erase_regions
::erase_regions(tcx
, &mut mir_map
));
858 // Option dance to work around the lack of stack once closures.
861 move || trans
::trans_crate(tcx
, &mir_map
, analysis
))
864 /// Run LLVM itself, producing a bitcode file, assembly file or object file
865 /// as a side effect.
866 pub fn phase_5_run_llvm_passes(sess
: &Session
,
867 trans
: &trans
::CrateTranslation
,
868 outputs
: &OutputFilenames
) {
869 if sess
.opts
.cg
.no_integrated_as
{
870 let mut map
= HashMap
::new();
871 map
.insert(OutputType
::Assembly
, None
);
872 time(sess
.time_passes(),
874 || write
::run_passes(sess
, trans
, &map
, outputs
));
876 write
::run_assembler(sess
, outputs
);
878 // Remove assembly source, unless --save-temps was specified
879 if !sess
.opts
.cg
.save_temps
{
880 fs
::remove_file(&outputs
.temp_path(OutputType
::Assembly
)).unwrap();
883 time(sess
.time_passes(),
885 || write
::run_passes(sess
, trans
, &sess
.opts
.output_types
, outputs
));
888 sess
.abort_if_errors();
891 /// Run the linker on any artifacts that resulted from the LLVM run.
892 /// This should produce either a finished executable or library.
893 pub fn phase_6_link_output(sess
: &Session
,
894 trans
: &trans
::CrateTranslation
,
895 outputs
: &OutputFilenames
) {
896 time(sess
.time_passes(),
898 || link
::link_binary(sess
, trans
, outputs
, &trans
.link
.crate_name
));
901 fn escape_dep_filename(filename
: &str) -> String
{
902 // Apparently clang and gcc *only* escape spaces:
903 // http://llvm.org/klaus/clang/commit/9d50634cfc268ecc9a7250226dd5ca0e945240d4
904 filename
.replace(" ", "\\ ")
907 fn write_out_deps(sess
: &Session
, outputs
: &OutputFilenames
, id
: &str) {
908 let mut out_filenames
= Vec
::new();
909 for output_type
in sess
.opts
.output_types
.keys() {
910 let file
= outputs
.path(*output_type
);
913 for output
in sess
.crate_types
.borrow().iter() {
914 let p
= link
::filename_for_input(sess
, *output
, id
, outputs
);
915 out_filenames
.push(p
);
919 out_filenames
.push(file
);
924 // Write out dependency rules to the dep-info file if requested
925 if !sess
.opts
.output_types
.contains_key(&OutputType
::DepInfo
) {
928 let deps_filename
= outputs
.path(OutputType
::DepInfo
);
931 (|| -> io
::Result
<()> {
932 // Build a list of files used to compile the output and
933 // write Makefile-compatible dependency rules
934 let files
: Vec
<String
> = sess
.codemap()
938 .filter(|fmap
| fmap
.is_real_file())
939 .filter(|fmap
| !fmap
.is_imported())
940 .map(|fmap
| escape_dep_filename(&fmap
.name
))
942 let mut file
= try
!(fs
::File
::create(&deps_filename
));
943 for path
in &out_filenames
{
944 try
!(write
!(file
, "{}: {}\n\n", path
.display(), files
.join(" ")));
947 // Emit a fake target for each input file to the compilation. This
948 // prevents `make` from spitting out an error if a file is later
949 // deleted. For more info see #28735
951 try
!(writeln
!(file
, "{}:", path
));
959 sess
.fatal(&format
!("error writing dependencies to `{}`: {}",
960 deps_filename
.display(),
966 pub fn collect_crate_types(session
: &Session
, attrs
: &[ast
::Attribute
]) -> Vec
<config
::CrateType
> {
967 // Unconditionally collect crate types from attributes to make them used
968 let attr_types
: Vec
<config
::CrateType
> =
971 if a
.check_name("crate_type") {
972 match a
.value_str() {
973 Some(ref n
) if *n
== "rlib" => {
974 Some(config
::CrateTypeRlib
)
976 Some(ref n
) if *n
== "dylib" => {
977 Some(config
::CrateTypeDylib
)
979 Some(ref n
) if *n
== "lib" => {
980 Some(config
::default_lib_output())
982 Some(ref n
) if *n
== "staticlib" => {
983 Some(config
::CrateTypeStaticlib
)
985 Some(ref n
) if *n
== "bin" => Some(config
::CrateTypeExecutable
),
987 session
.add_lint(lint
::builtin
::UNKNOWN_CRATE_TYPES
,
990 "invalid `crate_type` value".to_string());
994 session
.span_err(a
.span
, "`crate_type` requires a value");
995 session
.note("for example: `#![crate_type=\"lib\"]`");
1005 // If we're generating a test executable, then ignore all other output
1006 // styles at all other locations
1007 if session
.opts
.test
{
1008 return vec
![config
::CrateTypeExecutable
];
1011 // Only check command line flags if present. If no types are specified by
1012 // command line, then reuse the empty `base` Vec to hold the types that
1013 // will be found in crate attributes.
1014 let mut base
= session
.opts
.crate_types
.clone();
1015 if base
.is_empty() {
1016 base
.extend(attr_types
);
1017 if base
.is_empty() {
1018 base
.push(link
::default_output_for_target(session
));
1025 .filter(|crate_type
| {
1026 let res
= !link
::invalid_output_for_target(session
, *crate_type
);
1029 session
.warn(&format
!("dropping unsupported crate type `{}` for target `{}`",
1031 session
.opts
.target_triple
));
1039 pub fn collect_crate_metadata(session
: &Session
, _attrs
: &[ast
::Attribute
]) -> Vec
<String
> {
1040 session
.opts
.cg
.metadata
.clone()
1043 pub fn build_output_filenames(input
: &Input
,
1044 odir
: &Option
<PathBuf
>,
1045 ofile
: &Option
<PathBuf
>,
1046 attrs
: &[ast
::Attribute
],
1048 -> OutputFilenames
{
1051 // "-" as input file will cause the parser to read from stdin so we
1052 // have to make up a name
1053 // We want to toss everything after the final '.'
1054 let dirpath
= match *odir
{
1055 Some(ref d
) => d
.clone(),
1056 None
=> PathBuf
::new(),
1059 // If a crate name is present, we use it as the link name
1060 let stem
= sess
.opts
1063 .or_else(|| attr
::find_crate_name(attrs
).map(|n
| n
.to_string()))
1064 .unwrap_or(input
.filestem());
1067 out_directory
: dirpath
,
1069 single_output_file
: None
,
1070 extra
: sess
.opts
.cg
.extra_filename
.clone(),
1071 outputs
: sess
.opts
.output_types
.clone(),
1075 Some(ref out_file
) => {
1076 let unnamed_output_types
= sess
.opts
1079 .filter(|a
| a
.is_none())
1081 let ofile
= if unnamed_output_types
> 1 {
1082 sess
.warn("ignoring specified output filename because multiple outputs were \
1086 Some(out_file
.clone())
1089 sess
.warn("ignoring --out-dir flag due to -o flag.");
1092 let cur_dir
= Path
::new("");
1095 out_directory
: out_file
.parent().unwrap_or(cur_dir
).to_path_buf(),
1096 out_filestem
: out_file
.file_stem()
1097 .unwrap_or(OsStr
::new(""))
1101 single_output_file
: ofile
,
1102 extra
: sess
.opts
.cg
.extra_filename
.clone(),
1103 outputs
: sess
.opts
.output_types
.clone(),