Skip to content

a few minor cleanups #4946

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Dec 23, 2019
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion clippy_dev/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,7 @@ impl Lint {
name: name.to_lowercase(),
group: group.to_string(),
desc: NL_ESCAPE_RE.replace(&desc.replace("\\\"", "\""), "").to_string(),
deprecation: deprecation.map(std::string::ToString::to_string),
deprecation: deprecation.map(ToString::to_string),
module: module.to_string(),
}
}
Expand Down
4 changes: 1 addition & 3 deletions clippy_lints/src/cargo_common_metadata.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,8 +8,6 @@ use rustc::lint::{EarlyContext, EarlyLintPass, LintArray, LintPass};
use rustc_session::declare_tool_lint;
use syntax::{ast::*, source_map::DUMMY_SP};

use cargo_metadata;

declare_clippy_lint! {
/// **What it does:** Checks to see if all common metadata is defined in
/// `Cargo.toml`. See: https://rust-lang-nursery.github.io/api-guidelines/documentation.html#cargotoml-includes-all-common-metadata-c-metadata
Expand Down Expand Up @@ -56,7 +54,7 @@ fn is_empty_path(value: &Option<PathBuf>) -> bool {

fn is_empty_vec(value: &[String]) -> bool {
// This works because empty iterators return true
value.iter().all(std::string::String::is_empty)
value.iter().all(String::is_empty)
}

declare_lint_pass!(CargoCommonMetadata => [CARGO_COMMON_METADATA]);
Expand Down
2 changes: 1 addition & 1 deletion clippy_lints/src/consts.rs
Original file line number Diff line number Diff line change
Expand Up @@ -253,7 +253,7 @@ impl<'c, 'cc> ConstEvalLateContext<'c, 'cc> {
let res = self.tables.qpath_res(qpath, callee.hir_id);
if let Some(def_id) = res.opt_def_id();
let def_path: Vec<_> = self.lcx.get_def_path(def_id).into_iter().map(Symbol::as_str).collect();
let def_path: Vec<&str> = def_path.iter().map(|s| &**s).collect();
let def_path: Vec<&str> = def_path.iter().take(4).map(|s| &**s).collect();
if let ["core", "num", int_impl, "max_value"] = *def_path;
then {
let value = match int_impl {
Expand Down
1 change: 0 additions & 1 deletion clippy_lints/src/doc.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
use crate::utils::{match_type, paths, return_ty, span_lint};
use itertools::Itertools;
use pulldown_cmark;
use rustc::hir;
use rustc::impl_lint_pass;
use rustc::lint::{LateContext, LateLintPass, LintArray, LintPass};
Expand Down
6 changes: 1 addition & 5 deletions clippy_lints/src/eta_reduction.rs
Original file line number Diff line number Diff line change
Expand Up @@ -146,11 +146,7 @@ fn check_closure(cx: &LateContext<'_, '_>, expr: &Expr) {
}

/// Tries to determine the type for universal function call to be used instead of the closure
fn get_ufcs_type_name(
cx: &LateContext<'_, '_>,
method_def_id: def_id::DefId,
self_arg: &Expr,
) -> std::option::Option<String> {
fn get_ufcs_type_name(cx: &LateContext<'_, '_>, method_def_id: def_id::DefId, self_arg: &Expr) -> Option<String> {
let expected_type_of_self = &cx.tcx.fn_sig(method_def_id).inputs_and_output().skip_binder()[0];
let actual_type_of_self = &cx.tables.node_type(self_arg.hir_id);

Expand Down
11 changes: 6 additions & 5 deletions clippy_lints/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,8 @@ extern crate syntax_pos;
use rustc::lint::{self, LintId};
use rustc::session::Session;
use rustc_data_structures::fx::FxHashSet;
use toml;

use std::path::Path;

/// Macro used to declare a Clippy lint.
///
Expand Down Expand Up @@ -349,16 +350,16 @@ pub fn read_conf(args: &[syntax::ast::NestedMetaItem], sess: &Session) -> Conf {
let file_name = file_name.map(|file_name| {
if file_name.is_relative() {
sess.local_crate_source_file
.as_ref()
.and_then(|file| std::path::Path::new(&file).parent().map(std::path::Path::to_path_buf))
.unwrap_or_default()
.as_deref()
.and_then(Path::parent)
.unwrap_or_else(|| Path::new(""))
.join(file_name)
} else {
file_name
}
});

let (conf, errors) = utils::conf::read(file_name.as_ref().map(std::convert::AsRef::as_ref));
let (conf, errors) = utils::conf::read(file_name.as_ref().map(AsRef::as_ref));

// all conf errors are non-fatal, we just use the default conf in case of error
for error in errors {
Expand Down
1 change: 0 additions & 1 deletion clippy_lints/src/literal_representation.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,6 @@ use rustc::{declare_lint_pass, impl_lint_pass};
use rustc_errors::Applicability;
use rustc_session::declare_tool_lint;
use syntax::ast::*;
use syntax_pos;

declare_clippy_lint! {
/// **What it does:** Warns if a long integral or floating-point constant does
Expand Down
1 change: 0 additions & 1 deletion clippy_lints/src/multiple_crate_versions.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,6 @@ use rustc::lint::{EarlyContext, EarlyLintPass, LintArray, LintPass};
use rustc_session::declare_tool_lint;
use syntax::{ast::*, source_map::DUMMY_SP};

use cargo_metadata;
use itertools::Itertools;

declare_clippy_lint! {
Expand Down
1 change: 0 additions & 1 deletion clippy_lints/src/regex.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
use crate::consts::{constant, Constant};
use crate::utils::{is_expn_of, match_def_path, match_type, paths, span_help_and_lint, span_lint};
use if_chain::if_chain;
use regex_syntax;
use rustc::hir::*;
use rustc::impl_lint_pass;
use rustc::lint::{LateContext, LateLintPass, LintArray, LintPass};
Expand Down
2 changes: 0 additions & 2 deletions clippy_lints/src/utils/conf.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,6 @@ use std::io::Read;
use std::sync::Mutex;
use std::{env, fmt, fs, io, path};
use syntax::{ast, source_map};
use toml;

/// Gets the configuration file from arguments.
pub fn file_from_args(args: &[ast::NestedMetaItem]) -> Result<Option<path::PathBuf>, (&'static str, source_map::Span)> {
Expand Down Expand Up @@ -77,7 +76,6 @@ macro_rules! define_Conf {
}
$(
mod $rust_name {
use serde;
use serde::Deserialize;
crate fn deserialize<'de, D: serde::Deserializer<'de>>(deserializer: D)
-> Result<define_Conf!(TY $($ty)+), D::Error> {
Expand Down
2 changes: 0 additions & 2 deletions clippy_lints/src/utils/sugg.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,9 +5,7 @@ use crate::utils::{higher, snippet, snippet_opt, snippet_with_macro_callsite};
use matches::matches;
use rustc::hir;
use rustc::lint::{EarlyContext, LateContext, LintContext};
use rustc_errors;
use rustc_errors::Applicability;
use std;
use std::borrow::Cow;
use std::convert::TryInto;
use std::fmt::Display;
Expand Down
2 changes: 0 additions & 2 deletions clippy_lints/src/wildcard_dependencies.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,9 +4,7 @@ use rustc::lint::{EarlyContext, EarlyLintPass, LintArray, LintPass};
use rustc_session::declare_tool_lint;
use syntax::{ast::*, source_map::DUMMY_SP};

use cargo_metadata;
use if_chain::if_chain;
use semver;

declare_clippy_lint! {
/// **What it does:** Checks for wildcard dependencies in the `Cargo.toml`.
Expand Down
69 changes: 29 additions & 40 deletions src/driver.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
#![cfg_attr(feature = "deny-warnings", deny(warnings))]
#![feature(rustc_private)]
#![feature(str_strip)]

// FIXME: switch to something more ergonomic here, once available.
// (Currently there is no way to opt into sysroot crates without `extern crate`.)
Expand All @@ -18,6 +19,8 @@ use rustc_tools_util::*;

use lazy_static::lazy_static;
use std::borrow::Cow;
use std::env;
use std::ops::Deref;
use std::panic;
use std::path::{Path, PathBuf};
use std::process::{exit, Command};
Expand All @@ -26,42 +29,38 @@ mod lintlist;

/// If a command-line option matches `find_arg`, then apply the predicate `pred` on its value. If
/// true, then return it. The parameter is assumed to be either `--arg=value` or `--arg value`.
fn arg_value<'a>(
args: impl IntoIterator<Item = &'a String>,
fn arg_value<'a, T: Deref<Target = str>>(
args: &'a [T],
find_arg: &str,
pred: impl Fn(&str) -> bool,
) -> Option<&'a str> {
let mut args = args.into_iter().map(String::as_str);

let mut args = args.iter().map(Deref::deref);
while let Some(arg) = args.next() {
let arg: Vec<_> = arg.splitn(2, '=').collect();
if arg.get(0) != Some(&find_arg) {
let mut arg = arg.splitn(2, '=');
if arg.next() != Some(find_arg) {
continue;
}

let value = arg.get(1).cloned().or_else(|| args.next());
if value.as_ref().map_or(false, |p| pred(p)) {
return value;
match arg.next().or_else(|| args.next()) {
Some(v) if pred(v) => return Some(v),
_ => {},
}
}
None
}

#[test]
fn test_arg_value() {
let args: Vec<_> = ["--bar=bar", "--foobar", "123", "--foo"]
.iter()
.map(std::string::ToString::to_string)
.collect();

assert_eq!(arg_value(None, "--foobar", |_| true), None);
assert_eq!(arg_value(&args, "--bar", |_| false), None);
assert_eq!(arg_value(&args, "--bar", |_| true), Some("bar"));
assert_eq!(arg_value(&args, "--bar", |p| p == "bar"), Some("bar"));
assert_eq!(arg_value(&args, "--bar", |p| p == "foo"), None);
assert_eq!(arg_value(&args, "--foobar", |p| p == "foo"), None);
assert_eq!(arg_value(&args, "--foobar", |p| p == "123"), Some("123"));
assert_eq!(arg_value(&args, "--foo", |_| true), None);
let args = &["--bar=bar", "--foobar", "123", "--foo"];

assert_eq!(arg_value(&[] as &[&str], "--foobar", |_| true), None);
assert_eq!(arg_value(args, "--bar", |_| false), None);
assert_eq!(arg_value(args, "--bar", |_| true), Some("bar"));
assert_eq!(arg_value(args, "--bar", |p| p == "bar"), Some("bar"));
assert_eq!(arg_value(args, "--bar", |p| p == "foo"), None);
assert_eq!(arg_value(args, "--foobar", |p| p == "foo"), None);
assert_eq!(arg_value(args, "--foobar", |p| p == "123"), Some("123"));
assert_eq!(arg_value(args, "--foo", |_| true), None);
}

#[allow(clippy::too_many_lines)]
Expand Down Expand Up @@ -276,7 +275,7 @@ fn report_clippy_ice(info: &panic::PanicInfo<'_>, bug_report_url: &str) {
}

// If backtraces are enabled, also print the query stack
let backtrace = std::env::var_os("RUST_BACKTRACE").map_or(false, |x| &x != "0");
let backtrace = env::var_os("RUST_BACKTRACE").map_or(false, |x| &x != "0");

if backtrace {
TyCtxt::try_print_query_stack(&handler);
Expand All @@ -288,16 +287,14 @@ pub fn main() {
lazy_static::initialize(&ICE_HOOK);
exit(
rustc_driver::catch_fatal_errors(move || {
use std::env;
let mut orig_args: Vec<String> = env::args().collect();

if std::env::args().any(|a| a == "--version" || a == "-V") {
if orig_args.iter().any(|a| a == "--version" || a == "-V") {
let version_info = rustc_tools_util::get_version_info!();
println!("{}", version_info);
exit(0);
}

let mut orig_args: Vec<String> = env::args().collect();

// Get the sysroot, looking from most specific to this invocation to the least:
// - command line
// - runtime environment
Expand Down Expand Up @@ -350,7 +347,7 @@ pub fn main() {
}

let should_describe_lints = || {
let args: Vec<_> = std::env::args().collect();
let args: Vec<_> = env::args().collect();
args.windows(2).any(|args| {
args[1] == "help"
&& match args[0].as_str() {
Expand All @@ -368,15 +365,9 @@ pub fn main() {
// this conditional check for the --sysroot flag is there so users can call
// `clippy_driver` directly
// without having to pass --sysroot or anything
let mut args: Vec<String> = if have_sys_root_arg {
orig_args.clone()
} else {
orig_args
.clone()
.into_iter()
.chain(Some("--sysroot".to_owned()))
.chain(Some(sys_root))
.collect()
let mut args: Vec<String> = orig_args.clone();
if !have_sys_root_arg {
args.extend(vec!["--sysroot".into(), sys_root]);
};

// this check ensures that dependencies are built but not linted and the final
Expand All @@ -385,7 +376,7 @@ pub fn main() {
|| arg_value(&orig_args, "--cap-lints", |val| val == "allow").is_none();

if clippy_enabled {
args.extend_from_slice(&["--cfg".to_owned(), r#"feature="cargo-clippy""#.to_owned()]);
args.extend(vec!["--cfg".into(), r#"feature="cargo-clippy""#.into()]);
if let Ok(extra_args) = env::var("CLIPPY_ARGS") {
args.extend(extra_args.split("__CLIPPY_HACKERY__").filter_map(|s| {
if s.is_empty() {
Expand All @@ -396,12 +387,10 @@ pub fn main() {
}));
}
}

let mut clippy = ClippyCallbacks;
let mut default = rustc_driver::DefaultCallbacks;
let callbacks: &mut (dyn rustc_driver::Callbacks + Send) =
if clippy_enabled { &mut clippy } else { &mut default };
let args = args;
rustc_driver::run_compiler(&args, callbacks, None, None)
})
.and_then(|result| result)
Expand Down
1 change: 0 additions & 1 deletion tests/integration.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
#![cfg(feature = "integration")]

use git2::Repository;
use tempfile;

use std::env;
use std::process::Command;
Expand Down
1 change: 0 additions & 1 deletion tests/ui/inefficient_to_string.fixed
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@
#![deny(clippy::inefficient_to_string)]

use std::borrow::Cow;
use std::string::ToString;

fn main() {
let rstr: &str = "hello";
Expand Down
1 change: 0 additions & 1 deletion tests/ui/inefficient_to_string.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@
#![deny(clippy::inefficient_to_string)]

use std::borrow::Cow;
use std::string::ToString;

fn main() {
let rstr: &str = "hello";
Expand Down
12 changes: 6 additions & 6 deletions tests/ui/inefficient_to_string.stderr
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
error: calling `to_string` on `&&str`
--> $DIR/inefficient_to_string.rs:12:21
--> $DIR/inefficient_to_string.rs:11:21
|
LL | let _: String = rrstr.to_string();
| ^^^^^^^^^^^^^^^^^ help: try dereferencing the receiver: `(*rrstr).to_string()`
Expand All @@ -12,39 +12,39 @@ LL | #![deny(clippy::inefficient_to_string)]
= help: `&str` implements `ToString` through a slower blanket impl, but `str` has a fast specialization of `ToString`

error: calling `to_string` on `&&&str`
--> $DIR/inefficient_to_string.rs:13:21
--> $DIR/inefficient_to_string.rs:12:21
|
LL | let _: String = rrrstr.to_string();
| ^^^^^^^^^^^^^^^^^^ help: try dereferencing the receiver: `(**rrrstr).to_string()`
|
= help: `&&str` implements `ToString` through a slower blanket impl, but `str` has a fast specialization of `ToString`

error: calling `to_string` on `&&std::string::String`
--> $DIR/inefficient_to_string.rs:21:21
--> $DIR/inefficient_to_string.rs:20:21
|
LL | let _: String = rrstring.to_string();
| ^^^^^^^^^^^^^^^^^^^^ help: try dereferencing the receiver: `(*rrstring).to_string()`
|
= help: `&std::string::String` implements `ToString` through a slower blanket impl, but `std::string::String` has a fast specialization of `ToString`

error: calling `to_string` on `&&&std::string::String`
--> $DIR/inefficient_to_string.rs:22:21
--> $DIR/inefficient_to_string.rs:21:21
|
LL | let _: String = rrrstring.to_string();
| ^^^^^^^^^^^^^^^^^^^^^ help: try dereferencing the receiver: `(**rrrstring).to_string()`
|
= help: `&&std::string::String` implements `ToString` through a slower blanket impl, but `std::string::String` has a fast specialization of `ToString`

error: calling `to_string` on `&&std::borrow::Cow<'_, str>`
--> $DIR/inefficient_to_string.rs:30:21
--> $DIR/inefficient_to_string.rs:29:21
|
LL | let _: String = rrcow.to_string();
| ^^^^^^^^^^^^^^^^^ help: try dereferencing the receiver: `(*rrcow).to_string()`
|
= help: `&std::borrow::Cow<'_, str>` implements `ToString` through a slower blanket impl, but `std::borrow::Cow<'_, str>` has a fast specialization of `ToString`

error: calling `to_string` on `&&&std::borrow::Cow<'_, str>`
--> $DIR/inefficient_to_string.rs:31:21
--> $DIR/inefficient_to_string.rs:30:21
|
LL | let _: String = rrrcow.to_string();
| ^^^^^^^^^^^^^^^^^^ help: try dereferencing the receiver: `(**rrrcow).to_string()`
Expand Down