]> git.lizzy.rs Git - rust.git/blob - src/librustc_driver/driver.rs
Renamed phase to compilation_done
[rust.git] / src / librustc_driver / driver.rs
1 // Copyright 2012-2015 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
4 //
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
10
11 use rustc::hir;
12 use rustc::hir::{map as hir_map, FreevarMap, TraitMap};
13 use rustc::hir::def::DefMap;
14 use rustc::hir::lowering::lower_crate;
15 use rustc_mir as mir;
16 use rustc::mir::mir_map::MirMap;
17 use rustc::session::{Session, CompileResult, compile_result_from_err_count};
18 use rustc::session::config::{self, Input, OutputFilenames, OutputType};
19 use rustc::session::search_paths::PathKind;
20 use rustc::lint;
21 use rustc::middle::{self, dependency_format, stability, reachable};
22 use rustc::middle::privacy::AccessLevels;
23 use rustc::ty::{self, TyCtxt};
24 use rustc::util::common::time;
25 use rustc::util::nodemap::NodeSet;
26 use rustc_back::sha2::{Sha256, Digest};
27 use rustc_borrowck as borrowck;
28 use rustc_incremental;
29 use rustc_resolve::{MakeGlobMap, Resolver};
30 use rustc_metadata::macro_import;
31 use rustc_metadata::creader::read_local_crates;
32 use rustc_metadata::cstore::CStore;
33 use rustc_trans::back::{link, write};
34 use rustc_trans as trans;
35 use rustc_typeck as typeck;
36 use rustc_privacy;
37 use rustc_plugin::registry::Registry;
38 use rustc_plugin as plugin;
39 use rustc_passes::{ast_validation, no_asm, loops, consts, rvalues, static_recursion};
40 use rustc_const_eval::check_match;
41 use super::Compilation;
42
43 use serialize::json;
44
45 use std::collections::HashMap;
46 use std::env;
47 use std::ffi::{OsString, OsStr};
48 use std::fs;
49 use std::io::{self, Write};
50 use std::path::{Path, PathBuf};
51 use syntax::{ast, diagnostics, visit};
52 use syntax::attr::{self, AttrMetaMethods};
53 use syntax::fold::Folder;
54 use syntax::parse::{self, PResult, token};
55 use syntax::util::node_count::NodeCounter;
56 use syntax;
57 use syntax_ext;
58
59 #[derive(Clone)]
60 pub struct Resolutions {
61     pub def_map: DefMap,
62     pub freevars: FreevarMap,
63     pub trait_map: TraitMap,
64     pub maybe_unused_trait_imports: NodeSet,
65 }
66
67 pub fn compile_input(sess: &Session,
68                      cstore: &CStore,
69                      cfg: ast::CrateConfig,
70                      input: &Input,
71                      outdir: &Option<PathBuf>,
72                      output: &Option<PathBuf>,
73                      addl_plugins: Option<Vec<String>>,
74                      control: &CompileController) -> CompileResult {
75     macro_rules! controller_entry_point {
76         ($point: ident, $tsess: expr, $make_state: expr, $phase_result: expr) => {{
77             let state = &mut $make_state;
78             let phase_result: &CompileResult = &$phase_result;
79             if phase_result.is_ok() || control.$point.run_callback_on_error {
80                 (control.$point.callback)(state);
81             }
82
83             if control.$point.stop == Compilation::Stop {
84                 return compile_result_from_err_count($tsess.err_count());
85             }
86         }}
87     }
88
89     // We need nested scopes here, because the intermediate results can keep
90     // large chunks of memory alive and we want to free them as soon as
91     // possible to keep the peak memory usage low
92     let (outputs, trans) = {
93         let krate = match phase_1_parse_input(sess, cfg, input) {
94             Ok(krate) => krate,
95             Err(mut parse_error) => {
96                 parse_error.emit();
97                 return Err(1);
98             }
99         };
100
101         let krate = {
102             let mut compile_state = CompileState::state_after_parse(input,
103                                                                     sess,
104                                                                     outdir,
105                                                                     output,
106                                                                     krate,
107                                                                     &cstore);
108             controller_entry_point!(after_parse,
109                                     sess,
110                                     compile_state,
111                                     Ok(()));
112
113             compile_state.krate.unwrap()
114         };
115
116         let outputs = build_output_filenames(input, outdir, output, &krate.attrs, sess);
117         let id = link::find_crate_name(Some(sess), &krate.attrs, input);
118         let ExpansionResult { expanded_crate, defs, analysis, resolutions, mut hir_forest } = {
119             phase_2_configure_and_expand(
120                 sess, &cstore, krate, &id, addl_plugins, control.make_glob_map,
121                 |expanded_crate| {
122                     let mut state = CompileState::state_after_expand(
123                         input, sess, outdir, output, &cstore, expanded_crate, &id,
124                     );
125                     controller_entry_point!(after_expand, sess, state, Ok(()));
126                     Ok(())
127                 }
128             )?
129         };
130
131         write_out_deps(sess, &outputs, &id);
132
133         let arenas = ty::CtxtArenas::new();
134
135         // Construct the HIR map
136         let hir_map = time(sess.time_passes(),
137                            "indexing hir",
138                            || hir_map::map_crate(&mut hir_forest, defs));
139
140         {
141             let _ignore = hir_map.dep_graph.in_ignore();
142             controller_entry_point!(after_hir_lowering,
143                                     sess,
144                                     CompileState::state_after_hir_lowering(input,
145                                                                   sess,
146                                                                   outdir,
147                                                                   output,
148                                                                   &arenas,
149                                                                   &cstore,
150                                                                   &hir_map,
151                                                                   &analysis,
152                                                                   &resolutions,
153                                                                   &expanded_crate,
154                                                                   &hir_map.krate(),
155                                                                   &id),
156                                     Ok(()));
157         }
158
159         time(sess.time_passes(), "attribute checking", || {
160             hir::check_attr::check_crate(sess, &expanded_crate);
161         });
162
163         let opt_crate = if keep_ast(sess) {
164             Some(&expanded_crate)
165         } else {
166             drop(expanded_crate);
167             None
168         };
169
170         phase_3_run_analysis_passes(sess,
171                                     hir_map,
172                                     analysis,
173                                     resolutions,
174                                     &arenas,
175                                     &id,
176                                     |tcx, mir_map, analysis, result| {
177             {
178                 // Eventually, we will want to track plugins.
179                 let _ignore = tcx.dep_graph.in_ignore();
180
181                 let mut state = CompileState::state_after_analysis(input,
182                                                                    sess,
183                                                                    outdir,
184                                                                    output,
185                                                                    opt_crate,
186                                                                    tcx.map.krate(),
187                                                                    &analysis,
188                                                                    mir_map.as_ref(),
189                                                                    tcx,
190                                                                    &id);
191                 (control.after_analysis.callback)(&mut state);
192
193                 if control.after_analysis.stop == Compilation::Stop {
194                     return result.and_then(|_| Err(0usize));
195                 }
196             }
197
198             result?;
199
200             if log_enabled!(::log::INFO) {
201                 println!("Pre-trans");
202                 tcx.print_debug_stats();
203             }
204             let trans = phase_4_translate_to_llvm(tcx,
205                                                   mir_map.unwrap(),
206                                                   analysis);
207
208             if log_enabled!(::log::INFO) {
209                 println!("Post-trans");
210                 tcx.print_debug_stats();
211             }
212
213             // Discard interned strings as they are no longer required.
214             token::get_ident_interner().clear();
215
216             Ok((outputs, trans))
217         })??
218     };
219
220     let phase5_result = phase_5_run_llvm_passes(sess, &trans, &outputs);
221
222     controller_entry_point!(after_llvm,
223                             sess,
224                             CompileState::state_after_llvm(input, sess, outdir, output, &trans),
225                             phase5_result);
226     phase5_result?;
227
228     write::cleanup_llvm(&trans);
229
230     phase_6_link_output(sess, &trans, &outputs);
231
232     controller_entry_point!(compilation_done,
233                             sess,
234                             CompileState::state_when_compilation_done(input, sess, outdir, output),
235                             Ok(()));
236
237     Ok(())
238 }
239
240 fn keep_mtwt_tables(sess: &Session) -> bool {
241     sess.opts.debugging_opts.keep_mtwt_tables
242 }
243
244 fn keep_ast(sess: &Session) -> bool {
245     sess.opts.debugging_opts.keep_ast ||
246     sess.opts.debugging_opts.save_analysis ||
247     sess.opts.debugging_opts.save_analysis_csv
248 }
249
250 /// The name used for source code that doesn't originate in a file
251 /// (e.g. source from stdin or a string)
252 pub fn anon_src() -> String {
253     "<anon>".to_string()
254 }
255
256 pub fn source_name(input: &Input) -> String {
257     match *input {
258         // FIXME (#9639): This needs to handle non-utf8 paths
259         Input::File(ref ifile) => ifile.to_str().unwrap().to_string(),
260         Input::Str { ref name, .. } => name.clone(),
261     }
262 }
263
264 /// CompileController is used to customise compilation, it allows compilation to
265 /// be stopped and/or to call arbitrary code at various points in compilation.
266 /// It also allows for various flags to be set to influence what information gets
267 /// collected during compilation.
268 ///
269 /// This is a somewhat higher level controller than a Session - the Session
270 /// controls what happens in each phase, whereas the CompileController controls
271 /// whether a phase is run at all and whether other code (from outside the
272 /// the compiler) is run between phases.
273 ///
274 /// Note that if compilation is set to stop and a callback is provided for a
275 /// given entry point, the callback is called before compilation is stopped.
276 ///
277 /// Expect more entry points to be added in the future.
278 pub struct CompileController<'a> {
279     pub after_parse: PhaseController<'a>,
280     pub after_expand: PhaseController<'a>,
281     pub after_hir_lowering: PhaseController<'a>,
282     pub after_analysis: PhaseController<'a>,
283     pub after_llvm: PhaseController<'a>,
284     pub compilation_done: PhaseController<'a>,
285
286     pub make_glob_map: MakeGlobMap,
287 }
288
289 impl<'a> CompileController<'a> {
290     pub fn basic() -> CompileController<'a> {
291         CompileController {
292             after_parse: PhaseController::basic(),
293             after_expand: PhaseController::basic(),
294             after_hir_lowering: PhaseController::basic(),
295             after_analysis: PhaseController::basic(),
296             after_llvm: PhaseController::basic(),
297             compilation_done: PhaseController::basic(),
298             make_glob_map: MakeGlobMap::No,
299         }
300     }
301 }
302
303 pub struct PhaseController<'a> {
304     pub stop: Compilation,
305     // If true then the compiler will try to run the callback even if the phase
306     // ends with an error. Note that this is not always possible.
307     pub run_callback_on_error: bool,
308     pub callback: Box<Fn(&mut CompileState) + 'a>,
309 }
310
311 impl<'a> PhaseController<'a> {
312     pub fn basic() -> PhaseController<'a> {
313         PhaseController {
314             stop: Compilation::Continue,
315             run_callback_on_error: false,
316             callback: box |_| {},
317         }
318     }
319 }
320
321 /// State that is passed to a callback. What state is available depends on when
322 /// during compilation the callback is made. See the various constructor methods
323 /// (`state_*`) in the impl to see which data is provided for any given entry point.
324 pub struct CompileState<'a, 'b, 'ast: 'a, 'tcx: 'b> where 'ast: 'tcx {
325     pub input: &'a Input,
326     pub session: &'ast Session,
327     pub krate: Option<ast::Crate>,
328     pub cstore: Option<&'a CStore>,
329     pub crate_name: Option<&'a str>,
330     pub output_filenames: Option<&'a OutputFilenames>,
331     pub out_dir: Option<&'a Path>,
332     pub out_file: Option<&'a Path>,
333     pub arenas: Option<&'ast ty::CtxtArenas<'ast>>,
334     pub expanded_crate: Option<&'a ast::Crate>,
335     pub hir_crate: Option<&'a hir::Crate>,
336     pub ast_map: Option<&'a hir_map::Map<'ast>>,
337     pub resolutions: Option<&'a Resolutions>,
338     pub mir_map: Option<&'b MirMap<'tcx>>,
339     pub analysis: Option<&'a ty::CrateAnalysis<'a>>,
340     pub tcx: Option<TyCtxt<'b, 'tcx, 'tcx>>,
341     pub trans: Option<&'a trans::CrateTranslation>,
342 }
343
344 impl<'a, 'b, 'ast, 'tcx> CompileState<'a, 'b, 'ast, 'tcx> {
345     fn empty(input: &'a Input,
346              session: &'ast Session,
347              out_dir: &'a Option<PathBuf>)
348              -> CompileState<'a, 'b, 'ast, 'tcx> {
349         CompileState {
350             input: input,
351             session: session,
352             out_dir: out_dir.as_ref().map(|s| &**s),
353             out_file: None,
354             arenas: None,
355             krate: None,
356             cstore: None,
357             crate_name: None,
358             output_filenames: None,
359             expanded_crate: None,
360             hir_crate: None,
361             ast_map: None,
362             resolutions: None,
363             analysis: None,
364             mir_map: None,
365             tcx: None,
366             trans: None,
367         }
368     }
369
370     fn state_after_parse(input: &'a Input,
371                          session: &'ast Session,
372                          out_dir: &'a Option<PathBuf>,
373                          out_file: &'a Option<PathBuf>,
374                          krate: ast::Crate,
375                          cstore: &'a CStore)
376                          -> CompileState<'a, 'b, 'ast, 'tcx> {
377         CompileState {
378             krate: Some(krate),
379             cstore: Some(cstore),
380             out_file: out_file.as_ref().map(|s| &**s),
381             ..CompileState::empty(input, session, out_dir)
382         }
383     }
384
385     fn state_after_expand(input: &'a Input,
386                           session: &'ast Session,
387                           out_dir: &'a Option<PathBuf>,
388                           out_file: &'a Option<PathBuf>,
389                           cstore: &'a CStore,
390                           expanded_crate: &'a ast::Crate,
391                           crate_name: &'a str)
392                           -> CompileState<'a, 'b, 'ast, 'tcx> {
393         CompileState {
394             crate_name: Some(crate_name),
395             cstore: Some(cstore),
396             expanded_crate: Some(expanded_crate),
397             out_file: out_file.as_ref().map(|s| &**s),
398             ..CompileState::empty(input, session, out_dir)
399         }
400     }
401
402     fn state_after_hir_lowering(input: &'a Input,
403                                 session: &'ast Session,
404                                 out_dir: &'a Option<PathBuf>,
405                                 out_file: &'a Option<PathBuf>,
406                                 arenas: &'ast ty::CtxtArenas<'ast>,
407                                 cstore: &'a CStore,
408                                 hir_map: &'a hir_map::Map<'ast>,
409                                 analysis: &'a ty::CrateAnalysis,
410                                 resolutions: &'a Resolutions,
411                                 krate: &'a ast::Crate,
412                                 hir_crate: &'a hir::Crate,
413                                 crate_name: &'a str)
414                                 -> CompileState<'a, 'b, 'ast, 'tcx> {
415         CompileState {
416             crate_name: Some(crate_name),
417             arenas: Some(arenas),
418             cstore: Some(cstore),
419             ast_map: Some(hir_map),
420             analysis: Some(analysis),
421             resolutions: Some(resolutions),
422             expanded_crate: Some(krate),
423             hir_crate: Some(hir_crate),
424             out_file: out_file.as_ref().map(|s| &**s),
425             ..CompileState::empty(input, session, out_dir)
426         }
427     }
428
429     fn state_after_analysis(input: &'a Input,
430                             session: &'ast Session,
431                             out_dir: &'a Option<PathBuf>,
432                             out_file: &'a Option<PathBuf>,
433                             krate: Option<&'a ast::Crate>,
434                             hir_crate: &'a hir::Crate,
435                             analysis: &'a ty::CrateAnalysis<'a>,
436                             mir_map: Option<&'b MirMap<'tcx>>,
437                             tcx: TyCtxt<'b, 'tcx, 'tcx>,
438                             crate_name: &'a str)
439                             -> CompileState<'a, 'b, 'ast, 'tcx> {
440         CompileState {
441             analysis: Some(analysis),
442             mir_map: mir_map,
443             tcx: Some(tcx),
444             expanded_crate: krate,
445             hir_crate: Some(hir_crate),
446             crate_name: Some(crate_name),
447             out_file: out_file.as_ref().map(|s| &**s),
448             ..CompileState::empty(input, session, out_dir)
449         }
450     }
451
452
453     fn state_after_llvm(input: &'a Input,
454                         session: &'ast Session,
455                         out_dir: &'a Option<PathBuf>,
456                         out_file: &'a Option<PathBuf>,
457                         trans: &'a trans::CrateTranslation)
458                         -> CompileState<'a, 'b, 'ast, 'tcx> {
459         CompileState {
460             trans: Some(trans),
461             out_file: out_file.as_ref().map(|s| &**s),
462             ..CompileState::empty(input, session, out_dir)
463         }
464     }
465
466     fn state_when_compilation_done(input: &'a Input,
467                                     session: &'ast Session,
468                                     out_dir: &'a Option<PathBuf>,
469                                     out_file: &'a Option<PathBuf>)
470                                     -> CompileState<'a, 'b, 'ast, 'tcx> {
471         CompileState {
472             out_file: out_file.as_ref().map(|s| &**s),
473             ..CompileState::empty(input, session, out_dir)
474         }
475     }
476 }
477
478 pub fn phase_1_parse_input<'a>(sess: &'a Session,
479                                cfg: ast::CrateConfig,
480                                input: &Input)
481                                -> PResult<'a, ast::Crate> {
482     // These may be left in an incoherent state after a previous compile.
483     // `clear_tables` and `get_ident_interner().clear()` can be used to free
484     // memory, but they do not restore the initial state.
485     syntax::ext::mtwt::reset_tables();
486     token::reset_ident_interner();
487     let continue_after_error = sess.opts.continue_parse_after_error;
488     sess.diagnostic().set_continue_after_error(continue_after_error);
489
490     let krate = time(sess.time_passes(), "parsing", || {
491         match *input {
492             Input::File(ref file) => {
493                 parse::parse_crate_from_file(file, cfg.clone(), &sess.parse_sess)
494             }
495             Input::Str { ref input, ref name } => {
496                 parse::parse_crate_from_source_str(name.clone(),
497                                                    input.clone(),
498                                                    cfg.clone(),
499                                                    &sess.parse_sess)
500             }
501         }
502     })?;
503
504     sess.diagnostic().set_continue_after_error(true);
505
506     if sess.opts.debugging_opts.ast_json_noexpand {
507         println!("{}", json::as_json(&krate));
508     }
509
510     if sess.opts.debugging_opts.input_stats {
511         println!("Lines of code:             {}", sess.codemap().count_lines());
512         println!("Pre-expansion node count:  {}", count_nodes(&krate));
513     }
514
515     if let Some(ref s) = sess.opts.debugging_opts.show_span {
516         syntax::show_span::run(sess.diagnostic(), s, &krate);
517     }
518
519     Ok(krate)
520 }
521
522 fn count_nodes(krate: &ast::Crate) -> usize {
523     let mut counter = NodeCounter::new();
524     visit::walk_crate(&mut counter, krate);
525     counter.count
526 }
527
528 // For continuing compilation after a parsed crate has been
529 // modified
530
531 pub struct ExpansionResult<'a> {
532     pub expanded_crate: ast::Crate,
533     pub defs: hir_map::Definitions,
534     pub analysis: ty::CrateAnalysis<'a>,
535     pub resolutions: Resolutions,
536     pub hir_forest: hir_map::Forest,
537 }
538
539 /// Run the "early phases" of the compiler: initial `cfg` processing,
540 /// loading compiler plugins (including those from `addl_plugins`),
541 /// syntax expansion, secondary `cfg` expansion, synthesis of a test
542 /// harness if one is to be provided, injection of a dependency on the
543 /// standard library and prelude, and name resolution.
544 ///
545 /// Returns `None` if we're aborting after handling -W help.
546 pub fn phase_2_configure_and_expand<'a, F>(sess: &Session,
547                                            cstore: &CStore,
548                                            mut krate: ast::Crate,
549                                            crate_name: &'a str,
550                                            addl_plugins: Option<Vec<String>>,
551                                            make_glob_map: MakeGlobMap,
552                                            after_expand: F)
553                                            -> Result<ExpansionResult<'a>, usize>
554     where F: FnOnce(&ast::Crate) -> CompileResult,
555 {
556     let time_passes = sess.time_passes();
557
558     // strip before anything else because crate metadata may use #[cfg_attr]
559     // and so macros can depend on configuration variables, such as
560     //
561     //   #[macro_use] #[cfg(foo)]
562     //   mod bar { macro_rules! baz!(() => {{}}) }
563     //
564     // baz! should not use this definition unless foo is enabled.
565
566     krate = time(time_passes, "configuration", || {
567         let (krate, features) =
568             syntax::config::strip_unconfigured_items(krate, &sess.parse_sess, sess.opts.test);
569         // these need to be set "early" so that expansion sees `quote` if enabled.
570         *sess.features.borrow_mut() = features;
571         krate
572     });
573
574     *sess.crate_types.borrow_mut() = collect_crate_types(sess, &krate.attrs);
575     sess.crate_disambiguator.set(token::intern(&compute_crate_disambiguator(sess)));
576
577     time(time_passes, "recursion limit", || {
578         middle::recursion_limit::update_recursion_limit(sess, &krate);
579     });
580
581     krate = time(time_passes, "crate injection", || {
582         let alt_std_name = sess.opts.alt_std_name.clone();
583         syntax::std_inject::maybe_inject_crates_ref(&sess.parse_sess, krate, alt_std_name)
584     });
585
586     let mut addl_plugins = Some(addl_plugins);
587     let registrars = time(time_passes, "plugin loading", || {
588         plugin::load::load_plugins(sess,
589                                    &cstore,
590                                    &krate,
591                                    crate_name,
592                                    addl_plugins.take().unwrap())
593     });
594
595     let mut registry = Registry::new(sess, &krate);
596
597     time(time_passes, "plugin registration", || {
598         if sess.features.borrow().rustc_diagnostic_macros {
599             registry.register_macro("__diagnostic_used",
600                                     diagnostics::plugin::expand_diagnostic_used);
601             registry.register_macro("__register_diagnostic",
602                                     diagnostics::plugin::expand_register_diagnostic);
603             registry.register_macro("__build_diagnostic_array",
604                                     diagnostics::plugin::expand_build_diagnostic_array);
605         }
606
607         for registrar in registrars {
608             registry.args_hidden = Some(registrar.args);
609             (registrar.fun)(&mut registry);
610         }
611     });
612
613     let Registry { syntax_exts, early_lint_passes, late_lint_passes, lint_groups,
614                    llvm_passes, attributes, mir_passes, .. } = registry;
615
616     sess.track_errors(|| {
617         let mut ls = sess.lint_store.borrow_mut();
618         for pass in early_lint_passes {
619             ls.register_early_pass(Some(sess), true, pass);
620         }
621         for pass in late_lint_passes {
622             ls.register_late_pass(Some(sess), true, pass);
623         }
624
625         for (name, to) in lint_groups {
626             ls.register_group(Some(sess), true, name, to);
627         }
628
629         *sess.plugin_llvm_passes.borrow_mut() = llvm_passes;
630         sess.mir_passes.borrow_mut().extend(mir_passes);
631         *sess.plugin_attributes.borrow_mut() = attributes.clone();
632     })?;
633
634     // Lint plugins are registered; now we can process command line flags.
635     if sess.opts.describe_lints {
636         super::describe_lints(&sess.lint_store.borrow(), true);
637         return Err(0);
638     }
639     sess.track_errors(|| sess.lint_store.borrow_mut().process_command_line(sess))?;
640
641     krate = time(time_passes, "expansion", || {
642         // Windows dlls do not have rpaths, so they don't know how to find their
643         // dependencies. It's up to us to tell the system where to find all the
644         // dependent dlls. Note that this uses cfg!(windows) as opposed to
645         // targ_cfg because syntax extensions are always loaded for the host
646         // compiler, not for the target.
647         //
648         // This is somewhat of an inherently racy operation, however, as
649         // multiple threads calling this function could possibly continue
650         // extending PATH far beyond what it should. To solve this for now we
651         // just don't add any new elements to PATH which are already there
652         // within PATH. This is basically a targeted fix at #17360 for rustdoc
653         // which runs rustc in parallel but has been seen (#33844) to cause
654         // problems with PATH becoming too long.
655         let mut old_path = OsString::new();
656         if cfg!(windows) {
657             old_path = env::var_os("PATH").unwrap_or(old_path);
658             let mut new_path = sess.host_filesearch(PathKind::All)
659                                    .get_dylib_search_paths();
660             for path in env::split_paths(&old_path) {
661                 if !new_path.contains(&path) {
662                     new_path.push(path);
663                 }
664             }
665             env::set_var("PATH", &env::join_paths(new_path).unwrap());
666         }
667         let features = sess.features.borrow();
668         let cfg = syntax::ext::expand::ExpansionConfig {
669             crate_name: crate_name.to_string(),
670             features: Some(&features),
671             recursion_limit: sess.recursion_limit.get(),
672             trace_mac: sess.opts.debugging_opts.trace_macros,
673             should_test: sess.opts.test,
674         };
675         let mut loader = macro_import::MacroLoader::new(sess, &cstore, crate_name);
676         let mut ecx = syntax::ext::base::ExtCtxt::new(&sess.parse_sess,
677                                                       krate.config.clone(),
678                                                       cfg,
679                                                       &mut loader);
680         syntax_ext::register_builtins(&mut ecx.syntax_env);
681         let (ret, macro_names) = syntax::ext::expand::expand_crate(ecx,
682                                                                    syntax_exts,
683                                                                    krate);
684         if cfg!(windows) {
685             env::set_var("PATH", &old_path);
686         }
687         *sess.available_macros.borrow_mut() = macro_names;
688         ret
689     });
690
691     krate = time(time_passes, "maybe building test harness", || {
692         syntax::test::modify_for_testing(&sess.parse_sess,
693                                          sess.opts.test,
694                                          krate,
695                                          sess.diagnostic())
696     });
697
698     time(time_passes,
699          "checking for inline asm in case the target doesn't support it",
700          || no_asm::check_crate(sess, &krate));
701
702     // Needs to go *after* expansion to be able to check the results of macro expansion.
703     time(time_passes, "complete gated feature checking", || {
704         sess.track_errors(|| {
705             syntax::feature_gate::check_crate(&krate,
706                                               &sess.parse_sess,
707                                               &sess.features.borrow(),
708                                               &attributes,
709                                               sess.opts.unstable_features);
710         })
711     })?;
712
713     if sess.opts.debugging_opts.input_stats {
714         println!("Post-expansion node count: {}", count_nodes(&krate));
715     }
716
717     krate = assign_node_ids(sess, krate);
718
719     let resolver_arenas = Resolver::arenas();
720     let mut resolver = Resolver::new(sess, make_glob_map, &resolver_arenas);
721
722     // Collect defintions for def ids.
723     time(sess.time_passes(), "collecting defs", || resolver.definitions.collect(&krate));
724
725     time(sess.time_passes(), "external crate/lib resolution", || {
726         let defs = &resolver.definitions;
727         read_local_crates(sess, &cstore, defs, &krate, crate_name, &sess.dep_graph)
728     });
729
730     time(sess.time_passes(),
731          "early lint checks",
732          || lint::check_ast_crate(sess, &krate));
733
734     time(sess.time_passes(),
735          "AST validation",
736          || ast_validation::check_crate(sess, &krate));
737
738     time(sess.time_passes(), "name resolution", || -> CompileResult {
739         // Currently, we ignore the name resolution data structures for the purposes of dependency
740         // tracking. Instead we will run name resolution and include its output in the hash of each
741         // item, much like we do for macro expansion. In other words, the hash reflects not just
742         // its contents but the results of name resolution on those contents. Hopefully we'll push
743         // this back at some point.
744         let _ignore = sess.dep_graph.in_ignore();
745         resolver.build_reduced_graph(&krate);
746         resolver.resolve_imports();
747
748         // Since import resolution will eventually happen in expansion,
749         // don't perform `after_expand` until after import resolution.
750         after_expand(&krate)?;
751
752         resolver.resolve_crate(&krate);
753         Ok(())
754     })?;
755
756     // Lower ast -> hir.
757     let hir_forest = time(sess.time_passes(), "lowering ast -> hir", || {
758         hir_map::Forest::new(lower_crate(sess, &krate, &mut resolver), &sess.dep_graph)
759     });
760
761     // Discard MTWT tables that aren't required past lowering to HIR.
762     if !keep_mtwt_tables(sess) {
763         syntax::ext::mtwt::clear_tables();
764     }
765
766     Ok(ExpansionResult {
767         expanded_crate: krate,
768         defs: resolver.definitions,
769         analysis: ty::CrateAnalysis {
770             export_map: resolver.export_map,
771             access_levels: AccessLevels::default(),
772             reachable: NodeSet(),
773             name: crate_name,
774             glob_map: if resolver.make_glob_map { Some(resolver.glob_map) } else { None },
775         },
776         resolutions: Resolutions {
777             def_map: resolver.def_map,
778             freevars: resolver.freevars,
779             trait_map: resolver.trait_map,
780             maybe_unused_trait_imports: resolver.maybe_unused_trait_imports,
781         },
782         hir_forest: hir_forest
783     })
784 }
785
786 pub fn assign_node_ids(sess: &Session, krate: ast::Crate) -> ast::Crate {
787     use syntax::ptr::P;
788     use syntax::util::move_map::MoveMap;
789
790     struct NodeIdAssigner<'a> {
791         sess: &'a Session,
792     }
793
794     impl<'a> Folder for NodeIdAssigner<'a> {
795         fn new_id(&mut self, old_id: ast::NodeId) -> ast::NodeId {
796             assert_eq!(old_id, ast::DUMMY_NODE_ID);
797             self.sess.next_node_id()
798         }
799
800         fn fold_block(&mut self, block: P<ast::Block>) -> P<ast::Block> {
801             block.map(|mut block| {
802                 block.id = self.new_id(block.id);
803
804                 let stmt = block.stmts.pop();
805                 block.stmts = block.stmts.move_flat_map(|s| self.fold_stmt(s).into_iter());
806                 if let Some(ast::Stmt { node: ast::StmtKind::Expr(expr), span, .. }) = stmt {
807                     let expr = self.fold_expr(expr);
808                     block.stmts.push(ast::Stmt {
809                         id: expr.id,
810                         node: ast::StmtKind::Expr(expr),
811                         span: span,
812                     });
813                 } else if let Some(stmt) = stmt {
814                     block.stmts.extend(self.fold_stmt(stmt));
815                 }
816
817                 block
818             })
819         }
820     }
821
822     let krate = time(sess.time_passes(),
823                      "assigning node ids",
824                      || NodeIdAssigner { sess: sess }.fold_crate(krate));
825
826     if sess.opts.debugging_opts.ast_json {
827         println!("{}", json::as_json(&krate));
828     }
829
830     krate
831 }
832
833 /// Run the resolution, typechecking, region checking and other
834 /// miscellaneous analysis passes on the crate. Return various
835 /// structures carrying the results of the analysis.
836 pub fn phase_3_run_analysis_passes<'tcx, F, R>(sess: &'tcx Session,
837                                                hir_map: hir_map::Map<'tcx>,
838                                                mut analysis: ty::CrateAnalysis,
839                                                resolutions: Resolutions,
840                                                arenas: &'tcx ty::CtxtArenas<'tcx>,
841                                                name: &str,
842                                                f: F)
843                                                -> Result<R, usize>
844     where F: for<'a> FnOnce(TyCtxt<'a, 'tcx, 'tcx>,
845                             Option<MirMap<'tcx>>,
846                             ty::CrateAnalysis,
847                             CompileResult) -> R
848 {
849     macro_rules! try_with_f {
850         ($e: expr, ($t: expr, $m: expr, $a: expr)) => {
851             match $e {
852                 Ok(x) => x,
853                 Err(x) => {
854                     f($t, $m, $a, Err(x));
855                     return Err(x);
856                 }
857             }
858         }
859     }
860
861     let time_passes = sess.time_passes();
862
863     let lang_items = time(time_passes, "language item collection", || {
864         sess.track_errors(|| {
865             middle::lang_items::collect_language_items(&sess, &hir_map)
866         })
867     })?;
868
869     let named_region_map = time(time_passes,
870                                 "lifetime resolution",
871                                 || middle::resolve_lifetime::krate(sess,
872                                                                    &hir_map,
873                                                                    &resolutions.def_map))?;
874
875     time(time_passes,
876          "looking for entry point",
877          || middle::entry::find_entry_point(sess, &hir_map));
878
879     sess.plugin_registrar_fn.set(time(time_passes, "looking for plugin registrar", || {
880         plugin::build::find_plugin_registrar(sess.diagnostic(), &hir_map)
881     }));
882
883     let region_map = time(time_passes,
884                           "region resolution",
885                           || middle::region::resolve_crate(sess, &hir_map));
886
887     time(time_passes,
888          "loop checking",
889          || loops::check_crate(sess, &hir_map));
890
891     time(time_passes,
892               "static item recursion checking",
893               || static_recursion::check_crate(sess, &resolutions.def_map, &hir_map))?;
894
895     let index = stability::Index::new(&hir_map);
896
897     let trait_map = resolutions.trait_map;
898     TyCtxt::create_and_enter(sess,
899                              arenas,
900                              resolutions.def_map,
901                              named_region_map,
902                              hir_map,
903                              resolutions.freevars,
904                              resolutions.maybe_unused_trait_imports,
905                              region_map,
906                              lang_items,
907                              index,
908                              name,
909                              |tcx| {
910         time(time_passes,
911              "load_dep_graph",
912              || rustc_incremental::load_dep_graph(tcx));
913
914         // passes are timed inside typeck
915         try_with_f!(typeck::check_crate(tcx, trait_map), (tcx, None, analysis));
916
917         time(time_passes,
918              "const checking",
919              || consts::check_crate(tcx));
920
921         analysis.access_levels =
922             time(time_passes, "privacy checking", || {
923                 rustc_privacy::check_crate(tcx, &analysis.export_map)
924             });
925
926         // Do not move this check past lint
927         time(time_passes, "stability index", || {
928             tcx.stability.borrow_mut().build(tcx, &analysis.access_levels)
929         });
930
931         time(time_passes,
932              "intrinsic checking",
933              || middle::intrinsicck::check_crate(tcx));
934
935         time(time_passes,
936              "effect checking",
937              || middle::effect::check_crate(tcx));
938
939         time(time_passes,
940              "match checking",
941              || check_match::check_crate(tcx));
942
943         // this must run before MIR dump, because
944         // "not all control paths return a value" is reported here.
945         //
946         // maybe move the check to a MIR pass?
947         time(time_passes,
948              "liveness checking",
949              || middle::liveness::check_crate(tcx));
950
951         time(time_passes,
952              "rvalue checking",
953              || rvalues::check_crate(tcx));
954
955         let mut mir_map =
956             time(time_passes,
957                  "MIR dump",
958                  || mir::mir_map::build_mir_for_crate(tcx));
959
960         time(time_passes, "MIR passes", || {
961             let mut passes = sess.mir_passes.borrow_mut();
962             // Push all the built-in passes.
963             passes.push_hook(box mir::transform::dump_mir::DumpMir);
964             passes.push_pass(box mir::transform::simplify_cfg::SimplifyCfg::new("initial"));
965             passes.push_pass(box mir::transform::qualify_consts::QualifyAndPromoteConstants);
966             passes.push_pass(box mir::transform::type_check::TypeckMir);
967             passes.push_pass(
968                 box mir::transform::simplify_branches::SimplifyBranches::new("initial"));
969             passes.push_pass(box mir::transform::simplify_cfg::SimplifyCfg::new("qualify-consts"));
970             // And run everything.
971             passes.run_passes(tcx, &mut mir_map);
972         });
973
974         time(time_passes,
975              "borrow checking",
976              || borrowck::check_crate(tcx, &mir_map));
977
978         // Avoid overwhelming user with errors if type checking failed.
979         // I'm not sure how helpful this is, to be honest, but it avoids
980         // a
981         // lot of annoying errors in the compile-fail tests (basically,
982         // lint warnings and so on -- kindck used to do this abort, but
983         // kindck is gone now). -nmatsakis
984         if sess.err_count() > 0 {
985             return Ok(f(tcx, Some(mir_map), analysis, Err(sess.err_count())));
986         }
987
988         analysis.reachable =
989             time(time_passes,
990                  "reachability checking",
991                  || reachable::find_reachable(tcx, &analysis.access_levels));
992
993         time(time_passes, "death checking", || {
994             middle::dead::check_crate(tcx, &analysis.access_levels);
995         });
996
997         let ref lib_features_used =
998             time(time_passes,
999                  "stability checking",
1000                  || stability::check_unstable_api_usage(tcx));
1001
1002         time(time_passes, "unused lib feature checking", || {
1003             stability::check_unused_or_stable_features(&tcx.sess,
1004                                                        lib_features_used)
1005         });
1006
1007         time(time_passes,
1008              "lint checking",
1009              || lint::check_crate(tcx, &analysis.access_levels));
1010
1011         // The above three passes generate errors w/o aborting
1012         if sess.err_count() > 0 {
1013             return Ok(f(tcx, Some(mir_map), analysis, Err(sess.err_count())));
1014         }
1015
1016         Ok(f(tcx, Some(mir_map), analysis, Ok(())))
1017     })
1018 }
1019
1020 /// Run the translation phase to LLVM, after which the AST and analysis can
1021 pub fn phase_4_translate_to_llvm<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
1022                                            mut mir_map: MirMap<'tcx>,
1023                                            analysis: ty::CrateAnalysis)
1024                                            -> trans::CrateTranslation {
1025     let time_passes = tcx.sess.time_passes();
1026
1027     time(time_passes,
1028          "resolving dependency formats",
1029          || dependency_format::calculate(&tcx.sess));
1030
1031     // Run the passes that transform the MIR into a more suitable for translation
1032     // to LLVM code.
1033     time(time_passes, "Prepare MIR codegen passes", || {
1034         let mut passes = ::rustc::mir::transform::Passes::new();
1035         passes.push_hook(box mir::transform::dump_mir::DumpMir);
1036         passes.push_pass(box mir::transform::no_landing_pads::NoLandingPads);
1037         passes.push_pass(box mir::transform::simplify_cfg::SimplifyCfg::new("no-landing-pads"));
1038
1039         passes.push_pass(box mir::transform::erase_regions::EraseRegions);
1040
1041         passes.push_pass(box mir::transform::add_call_guards::AddCallGuards);
1042         passes.push_pass(box borrowck::ElaborateDrops);
1043         passes.push_pass(box mir::transform::no_landing_pads::NoLandingPads);
1044         passes.push_pass(box mir::transform::simplify_cfg::SimplifyCfg::new("elaborate-drops"));
1045
1046         passes.push_pass(box mir::transform::add_call_guards::AddCallGuards);
1047         passes.push_pass(box mir::transform::dump_mir::Marker("PreTrans"));
1048
1049         passes.run_passes(tcx, &mut mir_map);
1050     });
1051
1052     let translation =
1053         time(time_passes,
1054              "translation",
1055              move || trans::trans_crate(tcx, &mir_map, analysis));
1056
1057     time(time_passes,
1058          "assert dep graph",
1059          move || rustc_incremental::assert_dep_graph(tcx));
1060
1061     time(time_passes,
1062          "serialize dep graph",
1063          move || rustc_incremental::save_dep_graph(tcx));
1064
1065     translation
1066 }
1067
1068 /// Run LLVM itself, producing a bitcode file, assembly file or object file
1069 /// as a side effect.
1070 pub fn phase_5_run_llvm_passes(sess: &Session,
1071                                trans: &trans::CrateTranslation,
1072                                outputs: &OutputFilenames) -> CompileResult {
1073     if sess.opts.cg.no_integrated_as {
1074         let mut map = HashMap::new();
1075         map.insert(OutputType::Assembly, None);
1076         time(sess.time_passes(),
1077              "LLVM passes",
1078              || write::run_passes(sess, trans, &map, outputs));
1079
1080         write::run_assembler(sess, outputs);
1081
1082         // Remove assembly source, unless --save-temps was specified
1083         if !sess.opts.cg.save_temps {
1084             fs::remove_file(&outputs.temp_path(OutputType::Assembly)).unwrap();
1085         }
1086     } else {
1087         time(sess.time_passes(),
1088              "LLVM passes",
1089              || write::run_passes(sess, trans, &sess.opts.output_types, outputs));
1090     }
1091
1092     if sess.err_count() > 0 {
1093         Err(sess.err_count())
1094     } else {
1095         Ok(())
1096     }
1097 }
1098
1099 /// Run the linker on any artifacts that resulted from the LLVM run.
1100 /// This should produce either a finished executable or library.
1101 pub fn phase_6_link_output(sess: &Session,
1102                            trans: &trans::CrateTranslation,
1103                            outputs: &OutputFilenames) {
1104     time(sess.time_passes(),
1105          "linking",
1106          || link::link_binary(sess, trans, outputs, &trans.link.crate_name));
1107 }
1108
1109 fn escape_dep_filename(filename: &str) -> String {
1110     // Apparently clang and gcc *only* escape spaces:
1111     // http://llvm.org/klaus/clang/commit/9d50634cfc268ecc9a7250226dd5ca0e945240d4
1112     filename.replace(" ", "\\ ")
1113 }
1114
1115 fn write_out_deps(sess: &Session, outputs: &OutputFilenames, id: &str) {
1116     let mut out_filenames = Vec::new();
1117     for output_type in sess.opts.output_types.keys() {
1118         let file = outputs.path(*output_type);
1119         match *output_type {
1120             OutputType::Exe => {
1121                 for output in sess.crate_types.borrow().iter() {
1122                     let p = link::filename_for_input(sess, *output, id, outputs);
1123                     out_filenames.push(p);
1124                 }
1125             }
1126             _ => {
1127                 out_filenames.push(file);
1128             }
1129         }
1130     }
1131
1132     // Write out dependency rules to the dep-info file if requested
1133     if !sess.opts.output_types.contains_key(&OutputType::DepInfo) {
1134         return;
1135     }
1136     let deps_filename = outputs.path(OutputType::DepInfo);
1137
1138     let result =
1139         (|| -> io::Result<()> {
1140             // Build a list of files used to compile the output and
1141             // write Makefile-compatible dependency rules
1142             let files: Vec<String> = sess.codemap()
1143                                          .files
1144                                          .borrow()
1145                                          .iter()
1146                                          .filter(|fmap| fmap.is_real_file())
1147                                          .filter(|fmap| !fmap.is_imported())
1148                                          .map(|fmap| escape_dep_filename(&fmap.name))
1149                                          .collect();
1150             let mut file = fs::File::create(&deps_filename)?;
1151             for path in &out_filenames {
1152                 write!(file, "{}: {}\n\n", path.display(), files.join(" "))?;
1153             }
1154
1155             // Emit a fake target for each input file to the compilation. This
1156             // prevents `make` from spitting out an error if a file is later
1157             // deleted. For more info see #28735
1158             for path in files {
1159                 writeln!(file, "{}:", path)?;
1160             }
1161             Ok(())
1162         })();
1163
1164     match result {
1165         Ok(()) => {}
1166         Err(e) => {
1167             sess.fatal(&format!("error writing dependencies to `{}`: {}",
1168                                 deps_filename.display(),
1169                                 e));
1170         }
1171     }
1172 }
1173
1174 pub fn collect_crate_types(session: &Session, attrs: &[ast::Attribute]) -> Vec<config::CrateType> {
1175     // Unconditionally collect crate types from attributes to make them used
1176     let attr_types: Vec<config::CrateType> =
1177         attrs.iter()
1178              .filter_map(|a| {
1179                  if a.check_name("crate_type") {
1180                      match a.value_str() {
1181                          Some(ref n) if *n == "rlib" => {
1182                              Some(config::CrateTypeRlib)
1183                          }
1184                          Some(ref n) if *n == "dylib" => {
1185                              Some(config::CrateTypeDylib)
1186                          }
1187                          Some(ref n) if *n == "cdylib" => {
1188                              Some(config::CrateTypeCdylib)
1189                          }
1190                          Some(ref n) if *n == "lib" => {
1191                              Some(config::default_lib_output())
1192                          }
1193                          Some(ref n) if *n == "staticlib" => {
1194                              Some(config::CrateTypeStaticlib)
1195                          }
1196                          Some(ref n) if *n == "bin" => Some(config::CrateTypeExecutable),
1197                          Some(_) => {
1198                              session.add_lint(lint::builtin::UNKNOWN_CRATE_TYPES,
1199                                               ast::CRATE_NODE_ID,
1200                                               a.span,
1201                                               "invalid `crate_type` value".to_string());
1202                              None
1203                          }
1204                          _ => {
1205                              session.struct_span_err(a.span, "`crate_type` requires a value")
1206                                  .note("for example: `#![crate_type=\"lib\"]`")
1207                                  .emit();
1208                              None
1209                          }
1210                      }
1211                  } else {
1212                      None
1213                  }
1214              })
1215              .collect();
1216
1217     // If we're generating a test executable, then ignore all other output
1218     // styles at all other locations
1219     if session.opts.test {
1220         return vec![config::CrateTypeExecutable];
1221     }
1222
1223     // Only check command line flags if present. If no types are specified by
1224     // command line, then reuse the empty `base` Vec to hold the types that
1225     // will be found in crate attributes.
1226     let mut base = session.opts.crate_types.clone();
1227     if base.is_empty() {
1228         base.extend(attr_types);
1229         if base.is_empty() {
1230             base.push(link::default_output_for_target(session));
1231         }
1232         base.sort();
1233         base.dedup();
1234     }
1235
1236     base.into_iter()
1237         .filter(|crate_type| {
1238             let res = !link::invalid_output_for_target(session, *crate_type);
1239
1240             if !res {
1241                 session.warn(&format!("dropping unsupported crate type `{}` for target `{}`",
1242                                       *crate_type,
1243                                       session.opts.target_triple));
1244             }
1245
1246             res
1247         })
1248         .collect()
1249 }
1250
1251 pub fn compute_crate_disambiguator(session: &Session) -> String {
1252     let mut hasher = Sha256::new();
1253
1254     let mut metadata = session.opts.cg.metadata.clone();
1255     // We don't want the crate_disambiguator to dependent on the order
1256     // -C metadata arguments, so sort them:
1257     metadata.sort();
1258     // Every distinct -C metadata value is only incorporated once:
1259     metadata.dedup();
1260
1261     hasher.input_str("metadata");
1262     for s in &metadata {
1263         // Also incorporate the length of a metadata string, so that we generate
1264         // different values for `-Cmetadata=ab -Cmetadata=c` and
1265         // `-Cmetadata=a -Cmetadata=bc`
1266         hasher.input_str(&format!("{}", s.len())[..]);
1267         hasher.input_str(&s[..]);
1268     }
1269
1270     let mut hash = hasher.result_str();
1271
1272     // If this is an executable, add a special suffix, so that we don't get
1273     // symbol conflicts when linking against a library of the same name.
1274     if session.crate_types.borrow().contains(&config::CrateTypeExecutable) {
1275        hash.push_str("-exe");
1276     }
1277
1278     hash
1279 }
1280
1281 pub fn build_output_filenames(input: &Input,
1282                               odir: &Option<PathBuf>,
1283                               ofile: &Option<PathBuf>,
1284                               attrs: &[ast::Attribute],
1285                               sess: &Session)
1286                               -> OutputFilenames {
1287     match *ofile {
1288         None => {
1289             // "-" as input file will cause the parser to read from stdin so we
1290             // have to make up a name
1291             // We want to toss everything after the final '.'
1292             let dirpath = match *odir {
1293                 Some(ref d) => d.clone(),
1294                 None => PathBuf::new(),
1295             };
1296
1297             // If a crate name is present, we use it as the link name
1298             let stem = sess.opts
1299                            .crate_name
1300                            .clone()
1301                            .or_else(|| attr::find_crate_name(attrs).map(|n| n.to_string()))
1302                            .unwrap_or(input.filestem());
1303
1304             OutputFilenames {
1305                 out_directory: dirpath,
1306                 out_filestem: stem,
1307                 single_output_file: None,
1308                 extra: sess.opts.cg.extra_filename.clone(),
1309                 outputs: sess.opts.output_types.clone(),
1310             }
1311         }
1312
1313         Some(ref out_file) => {
1314             let unnamed_output_types = sess.opts
1315                                            .output_types
1316                                            .values()
1317                                            .filter(|a| a.is_none())
1318                                            .count();
1319             let ofile = if unnamed_output_types > 1 {
1320                 sess.warn("ignoring specified output filename because multiple outputs were \
1321                            requested");
1322                 None
1323             } else {
1324                 Some(out_file.clone())
1325             };
1326             if *odir != None {
1327                 sess.warn("ignoring --out-dir flag due to -o flag.");
1328             }
1329
1330             let cur_dir = Path::new("");
1331
1332             OutputFilenames {
1333                 out_directory: out_file.parent().unwrap_or(cur_dir).to_path_buf(),
1334                 out_filestem: out_file.file_stem()
1335                                       .unwrap_or(OsStr::new(""))
1336                                       .to_str()
1337                                       .unwrap()
1338                                       .to_string(),
1339                 single_output_file: ofile,
1340                 extra: sess.opts.cg.extra_filename.clone(),
1341                 outputs: sess.opts.output_types.clone(),
1342             }
1343         }
1344     }
1345 }