about summary refs log tree commit diff
path: root/src/librustc_driver/lib.rs
diff options
context:
space:
mode:
Diffstat (limited to 'src/librustc_driver/lib.rs')
-rw-r--r--src/librustc_driver/lib.rs174
1 files changed, 73 insertions, 101 deletions
diff --git a/src/librustc_driver/lib.rs b/src/librustc_driver/lib.rs
index 0514bd20c98..276b7290c2e 100644
--- a/src/librustc_driver/lib.rs
+++ b/src/librustc_driver/lib.rs
@@ -89,6 +89,7 @@ use rustc_codegen_utils::codegen_backend::CodegenBackend;
 use serialize::json::ToJson;
 
 use std::any::Any;
+use std::borrow::Cow;
 use std::cmp::max;
 use std::default::Default;
 use std::env::consts::{DLL_PREFIX, DLL_SUFFIX};
@@ -136,9 +137,7 @@ pub mod target_features {
                              codegen_backend: &dyn CodegenBackend) {
         let tf = Symbol::intern("target_feature");
 
-        for feat in codegen_backend.target_features(sess) {
-            cfg.insert((tf, Some(feat)));
-        }
+        cfg.extend(codegen_backend.target_features(sess).into_iter().map(|feat| (tf, Some(feat))));
 
         if sess.crt_static_feature() {
             cfg.insert((tf, Some(Symbol::intern("crt-static"))));
@@ -152,21 +151,14 @@ pub const EXIT_SUCCESS: isize = 0;
 /// Exit status code used for compilation failures and  invalid flags.
 pub const EXIT_FAILURE: isize = 1;
 
-const BUG_REPORT_URL: &'static str = "https://github.com/rust-lang/rust/blob/master/CONTRIBUTING.\
-                                      md#bug-reports";
-
-const ICE_REPORT_COMPILER_FLAGS: &'static [&'static str] = &[
-    "Z",
-    "C",
-    "crate-type",
-];
-const ICE_REPORT_COMPILER_FLAGS_EXCLUDE: &'static [&'static str] = &[
-    "metadata",
-    "extra-filename",
-];
-const ICE_REPORT_COMPILER_FLAGS_STRIP_VALUE: &'static [&'static str] = &[
-    "incremental",
-];
+const BUG_REPORT_URL: &str = "https://github.com/rust-lang/rust/blob/master/CONTRIBUTING.\
+                              md#bug-reports";
+
+const ICE_REPORT_COMPILER_FLAGS: &[&str] = &["Z", "C", "crate-type"];
+
+const ICE_REPORT_COMPILER_FLAGS_EXCLUDE: &[&str] = &["metadata", "extra-filename"];
+
+const ICE_REPORT_COMPILER_FLAGS_STRIP_VALUE: &[&str] = &["incremental"];
 
 pub fn abort_on_err<T>(result: Result<T, CompileIncomplete>, sess: &Session) -> T {
     match result {
@@ -195,14 +187,16 @@ pub fn run<F>(run_compiler: F) -> isize
                     }
                     None => {
                         let emitter =
-                            errors::emitter::EmitterWriter::stderr(errors::ColorConfig::Auto,
-                                                                None,
-                                                                true,
-                                                                false);
+                            errors::emitter::EmitterWriter::stderr(
+                                errors::ColorConfig::Auto,
+                                None,
+                                true,
+                                false
+                            );
                         let handler = errors::Handler::with_emitter(true, false, Box::new(emitter));
                         handler.emit(&MultiSpan::new(),
-                                    "aborting due to previous error(s)",
-                                    errors::Level::Fatal);
+                                     "aborting due to previous error(s)",
+                                     errors::Level::Fatal);
                         panic::resume_unwind(Box::new(errors::FatalErrorMarker));
                     }
                 }
@@ -224,15 +218,10 @@ fn load_backend_from_dylib(path: &Path) -> fn() -> Box<dyn CodegenBackend> {
     // available for future dynamic libraries opened. This is currently used by
     // loading LLVM and then making its symbols available for other dynamic
     // libraries.
-    let lib = match DynamicLibrary::open_global_now(path) {
-        Ok(lib) => lib,
-        Err(err) => {
-            let err = format!("couldn't load codegen backend {:?}: {:?}",
-                              path,
-                              err);
-            early_error(ErrorOutputType::default(), &err);
-        }
-    };
+    let lib = DynamicLibrary::open_global_now(path).unwrap_or_else(|err| {
+        let err = format!("couldn't load codegen backend {:?}: {:?}", path, err);
+        early_error(ErrorOutputType::default(), &err);
+    });
     unsafe {
         match lib.symbol("__rustc_codegen_backend") {
             Ok(f) => {
@@ -328,37 +317,30 @@ fn get_codegen_sysroot(backend_name: &str) -> fn() -> Box<dyn CodegenBackend> {
     let sysroot = sysroot_candidates.iter()
         .map(|sysroot| {
             let libdir = filesearch::relative_target_lib_path(&sysroot, &target);
-            sysroot.join(libdir)
-                .with_file_name(option_env!("CFG_CODEGEN_BACKENDS_DIR")
-                                .unwrap_or("codegen-backends"))
+            sysroot.join(libdir).with_file_name(
+                option_env!("CFG_CODEGEN_BACKENDS_DIR").unwrap_or("codegen-backends"))
         })
         .filter(|f| {
             info!("codegen backend candidate: {}", f.display());
             f.exists()
         })
         .next();
-    let sysroot = match sysroot {
-        Some(path) => path,
-        None => {
-            let candidates = sysroot_candidates.iter()
-                .map(|p| p.display().to_string())
-                .collect::<Vec<_>>()
-                .join("\n* ");
-            let err = format!("failed to find a `codegen-backends` folder \
-                               in the sysroot candidates:\n* {}", candidates);
-            early_error(ErrorOutputType::default(), &err);
-        }
-    };
+    let sysroot = sysroot.unwrap_or_else(|| {
+        let candidates = sysroot_candidates.iter()
+            .map(|p| p.display().to_string())
+            .collect::<Vec<_>>()
+            .join("\n* ");
+        let err = format!("failed to find a `codegen-backends` folder \
+                           in the sysroot candidates:\n* {}", candidates);
+        early_error(ErrorOutputType::default(), &err);
+    });
     info!("probing {} for a codegen backend", sysroot.display());
 
-    let d = match sysroot.read_dir() {
-        Ok(d) => d,
-        Err(e) => {
-            let err = format!("failed to load default codegen backend, couldn't \
-                               read `{}`: {}", sysroot.display(), e);
-            early_error(ErrorOutputType::default(), &err);
-        }
-    };
+    let d = sysroot.read_dir().unwrap_or_else(|e| {
+        let err = format!("failed to load default codegen backend, couldn't \
+                           read `{}`: {}", sysroot.display(), e);
+        early_error(ErrorOutputType::default(), &err);
+    });
 
     let mut file: Option<PathBuf> = None;
 
@@ -378,8 +360,8 @@ fn get_codegen_sysroot(backend_name: &str) -> fn() -> Box<dyn CodegenBackend> {
         }
         if let Some(ref prev) = file {
             let err = format!("duplicate codegen backends found\n\
-                first:  {}\n\
-                second: {}\n\
+                               first:  {}\n\
+                               second: {}\n\
             ", prev.display(), path.display());
             early_error(ErrorOutputType::default(), &err);
         }
@@ -391,7 +373,7 @@ fn get_codegen_sysroot(backend_name: &str) -> fn() -> Box<dyn CodegenBackend> {
         None => {
             let err = format!("failed to load default codegen backend for `{}`, \
                                no appropriate codegen dylib found in `{}`",
-                               backend_name, sysroot.display());
+                              backend_name, sysroot.display());
             early_error(ErrorOutputType::default(), &err);
         }
     }
@@ -578,7 +560,7 @@ pub fn set_sigpipe_handler() {
     unsafe {
         // Set the SIGPIPE signal handler, so that an EPIPE
         // will cause rustc to terminate, as expected.
-        assert!(libc::signal(libc::SIGPIPE, libc::SIG_DFL) != libc::SIG_ERR);
+        assert_ne!(libc::signal(libc::SIGPIPE, libc::SIG_DFL), libc::SIG_ERR);
     }
 }
 
@@ -996,7 +978,7 @@ impl RustcDefaultCalls {
                          input: &Input)
                          -> Compilation {
         let r = matches.opt_strs("Z");
-        if r.contains(&("ls".to_string())) {
+        if r.iter().any(|s| *s == "ls") {
             match input {
                 &Input::File(ref ifile) => {
                     let path = &(*ifile);
@@ -1015,7 +997,7 @@ impl RustcDefaultCalls {
             return Compilation::Stop;
         }
 
-        return Compilation::Continue;
+        Compilation::Continue
     }
 
 
@@ -1028,7 +1010,7 @@ impl RustcDefaultCalls {
         use rustc::session::config::PrintRequest::*;
         // PrintRequest::NativeStaticLibs is special - printed during linking
         // (empty iterator returns true)
-        if sess.opts.prints.iter().all(|&p| p==PrintRequest::NativeStaticLibs) {
+        if sess.opts.prints.iter().all(|&p| p == PrintRequest::NativeStaticLibs) {
             return Compilation::Continue;
         }
 
@@ -1055,10 +1037,8 @@ impl RustcDefaultCalls {
                 Sysroot => println!("{}", sess.sysroot().display()),
                 TargetSpec => println!("{}", sess.target.target.to_json().pretty()),
                 FileNames | CrateName => {
-                    let input = match input {
-                        Some(input) => input,
-                        None => early_error(ErrorOutputType::default(), "no input file provided"),
-                    };
+                    let input = input.unwrap_or_else(||
+                        early_error(ErrorOutputType::default(), "no input file provided"));
                     let attrs = attrs.as_ref().unwrap();
                     let t_outputs = driver::build_output_filenames(input, odir, ofile, attrs, sess);
                     let id = rustc_codegen_utils::link::find_crate_name(Some(sess), attrs, input);
@@ -1074,18 +1054,14 @@ impl RustcDefaultCalls {
                             &id,
                             &t_outputs
                         );
-                        println!("{}",
-                                 fname.file_name()
-                                      .unwrap()
-                                      .to_string_lossy());
+                        println!("{}", fname.file_name().unwrap().to_string_lossy());
                     }
                 }
                 Cfg => {
                     let allow_unstable_cfg = UnstableFeatures::from_environment()
                         .is_nightly_build();
 
-                    let mut cfgs = Vec::new();
-                    for &(name, ref value) in sess.parse_sess.config.iter() {
+                    let mut cfgs = sess.parse_sess.config.iter().filter_map(|&(name, ref value)| {
                         let gated_cfg = GatedCfg::gate(&ast::MetaItem {
                             ident: ast::Path::from_ident(ast::Ident::with_empty_ctxt(name)),
                             node: ast::MetaItemKind::Word,
@@ -1104,16 +1080,16 @@ impl RustcDefaultCalls {
                         let value = value.as_ref().map(|s| s.as_ref());
                         if name != "target_feature" || value != Some("crt-static") {
                             if !allow_unstable_cfg && gated_cfg.is_some() {
-                                continue;
+                                return None
                             }
                         }
 
-                        cfgs.push(if let Some(value) = value {
-                            format!("{}=\"{}\"", name, value)
+                        if let Some(value) = value {
+                            Some(format!("{}=\"{}\"", name, value))
                         } else {
-                            name.to_string()
-                        });
-                    }
+                            Some(name.to_string())
+                        }
+                    }).collect::<Vec<String>>();
 
                     cfgs.sort();
                     for cfg in cfgs {
@@ -1150,9 +1126,8 @@ fn commit_date_str() -> Option<&'static str> {
 pub fn version(binary: &str, matches: &getopts::Matches) {
     let verbose = matches.opt_present("verbose");
 
-    println!("{} {}",
-             binary,
-             option_env!("CFG_VERSION").unwrap_or("unknown version"));
+    println!("{} {}", binary, option_env!("CFG_VERSION").unwrap_or("unknown version"));
+
     if verbose {
         fn unw(x: Option<&str>) -> &str {
             x.unwrap_or("unknown")
@@ -1176,7 +1151,7 @@ fn usage(verbose: bool, include_unstable_options: bool) {
     for option in groups.iter().filter(|x| include_unstable_options || x.is_stable()) {
         (option.apply)(&mut options);
     }
-    let message = "Usage: rustc [OPTIONS] INPUT".to_string();
+    let message = "Usage: rustc [OPTIONS] INPUT";
     let nightly_help = if nightly_options::is_nightly_build() {
         "\n    -Z help             Print internal options for debugging rustc"
     } else {
@@ -1191,7 +1166,7 @@ fn usage(verbose: bool, include_unstable_options: bool) {
     -C help             Print codegen options
     -W help             \
               Print 'lint' options and default settings{}{}\n",
-             options.usage(&message),
+             options.usage(message),
              nightly_help,
              verbose_help);
 }
@@ -1273,8 +1248,6 @@ Available lint options:
 
     print_lints(builtin);
 
-
-
     let max_name_len = max("warnings".len(),
                            plugin_groups.iter()
                                         .chain(&builtin_groups)
@@ -1407,10 +1380,8 @@ pub fn handle_options(args: &[String]) -> Option<getopts::Matches> {
     for option in config::rustc_optgroups() {
         (option.apply)(&mut options);
     }
-    let matches = match options.parse(args) {
-        Ok(m) => m,
-        Err(f) => early_error(ErrorOutputType::default(), &f.to_string()),
-    };
+    let matches = options.parse(args).unwrap_or_else(|f|
+        early_error(ErrorOutputType::default(), &f.to_string()));
 
     // For all options we just parsed, we check a few aspects:
     //
@@ -1452,6 +1423,7 @@ pub fn handle_options(args: &[String]) -> Option<getopts::Matches> {
     }
 
     let cg_flags = matches.opt_strs("C");
+
     if cg_flags.iter().any(|x| *x == "help") {
         describe_codegen_flags();
         return None;
@@ -1462,7 +1434,7 @@ pub fn handle_options(args: &[String]) -> Option<getopts::Matches> {
                    "the --no-stack-check flag is deprecated and does nothing");
     }
 
-    if cg_flags.contains(&"passes=list".to_string()) {
+    if cg_flags.iter().any(|x| *x == "passes=list") {
         get_codegen_sysroot("llvm")().print_passes();
         return None;
     }
@@ -1500,7 +1472,7 @@ pub fn in_named_rustc_thread<F, R>(name: String, f: F) -> Result<R, Box<dyn Any
     // Temporarily have stack size set to 16MB to deal with nom-using crates failing
     const STACK_SIZE: usize = 16 * 1024 * 1024; // 16MB
 
-    #[cfg(all(unix,not(target_os = "haiku")))]
+    #[cfg(all(unix, not(target_os = "haiku")))]
     let spawn_thread = unsafe {
         // Fetch the current resource limits
         let mut rlim = libc::rlimit {
@@ -1554,7 +1526,7 @@ pub fn in_named_rustc_thread<F, R>(name: String, f: F) -> Result<R, Box<dyn Any
         }
     };
 
-    #[cfg(not(any(windows,unix)))]
+    #[cfg(not(any(windows, unix)))]
     let spawn_thread = true;
 
     // The or condition is added from backward compatibility.
@@ -1632,7 +1604,7 @@ fn extra_compiler_flags() -> Option<(Vec<String>, bool)> {
         }
     }
 
-    if result.len() > 0 {
+    if !result.is_empty() {
         Some((result, excluded_cargo_defaults))
     } else {
         None
@@ -1680,25 +1652,25 @@ pub fn monitor<F: FnOnce() + Send + 'static>(f: F) -> Result<(), CompilationFail
                              errors::Level::Bug);
             }
 
-            let mut xs = vec![
-                "the compiler unexpectedly panicked. this is a bug.".to_string(),
-                format!("we would appreciate a bug report: {}", BUG_REPORT_URL),
+            let mut xs: Vec<Cow<'static, str>> = vec![
+                "the compiler unexpectedly panicked. this is a bug.".into(),
+                format!("we would appreciate a bug report: {}", BUG_REPORT_URL).into(),
                 format!("rustc {} running on {}",
                         option_env!("CFG_VERSION").unwrap_or("unknown_version"),
-                        config::host_triple()),
+                        config::host_triple()).into(),
             ];
 
             if let Some((flags, excluded_cargo_defaults)) = extra_compiler_flags() {
-                xs.push(format!("compiler flags: {}", flags.join(" ")));
+                xs.push(format!("compiler flags: {}", flags.join(" ")).into());
 
                 if excluded_cargo_defaults {
-                    xs.push("some of the compiler flags provided by cargo are hidden".to_string());
+                    xs.push("some of the compiler flags provided by cargo are hidden".into());
                 }
             }
 
             for note in &xs {
                 handler.emit(&MultiSpan::new(),
-                             &note,
+                             note,
                              errors::Level::Note);
             }