1
Fork 0

Format code

This commit is contained in:
Mateusz Mikuła 2018-05-22 10:21:42 +02:00 committed by Mateusz Mikuła
parent e4b954ea92
commit 3c6503eb4b
11 changed files with 134 additions and 129 deletions

View file

@ -13,12 +13,12 @@
//! This build script was originally taken from the Rocket web framework: //! This build script was originally taken from the Rocket web framework:
//! https://github.com/SergioBenitez/Rocket //! https://github.com/SergioBenitez/Rocket
extern crate rustc_version;
extern crate ansi_term; extern crate ansi_term;
extern crate rustc_version;
use std::env;
use rustc_version::{version_meta, version_meta_for, Channel, Version, VersionMeta};
use ansi_term::Colour::Red; use ansi_term::Colour::Red;
use rustc_version::{version_meta, version_meta_for, Channel, Version, VersionMeta};
use std::env;
fn main() { fn main() {
check_rustc_version(); check_rustc_version();
@ -31,42 +31,48 @@ fn main() {
fn check_rustc_version() { fn check_rustc_version() {
let string = include_str!("min_version.txt"); let string = include_str!("min_version.txt");
let min_version_meta = version_meta_for(string) let min_version_meta = version_meta_for(string).expect("Could not parse version string in min_version.txt");
.expect("Could not parse version string in min_version.txt"); let current_version_meta = version_meta().expect("Could not retrieve current rustc version information from ENV");
let current_version_meta = version_meta()
.expect("Could not retrieve current rustc version information from ENV");
let min_version = min_version_meta.clone().semver; let min_version = min_version_meta.clone().semver;
let min_date_str = min_version_meta.clone().commit_date let min_date_str = min_version_meta
.clone()
.commit_date
.expect("min_version.txt does not contain a rustc commit date"); .expect("min_version.txt does not contain a rustc commit date");
// Dev channel (rustc built from git) does not have any date or commit information in rustc -vV // Dev channel (rustc built from git) does not have any date or commit information in rustc -vV
// `current_version_meta.commit_date` would crash, so we return early here. // `current_version_meta.commit_date` would crash, so we return early here.
if current_version_meta.channel == Channel::Dev { if current_version_meta.channel == Channel::Dev {
return return;
} }
let current_version = current_version_meta.clone().semver; let current_version = current_version_meta.clone().semver;
let current_date_str = current_version_meta.clone().commit_date let current_date_str = current_version_meta
.clone()
.commit_date
.expect("current rustc version information does not contain a rustc commit date"); .expect("current rustc version information does not contain a rustc commit date");
let print_version_err = |version: &Version, date: &str| { let print_version_err = |version: &Version, date: &str| {
eprintln!("> {} {}. {} {}.\n", eprintln!(
"Installed rustc version is:", "> {} {}. {} {}.\n",
format!("{} ({})", version, date), "Installed rustc version is:",
"Minimum required rustc version:", format!("{} ({})", version, date),
format!("{} ({})", min_version, min_date_str)); "Minimum required rustc version:",
format!("{} ({})", min_version, min_date_str)
);
}; };
if !correct_channel(&current_version_meta) { if !correct_channel(&current_version_meta) {
eprintln!("\n{} {}", eprintln!(
Red.bold().paint("error:"), "\n{} {}",
"clippy requires a nightly version of Rust."); Red.bold().paint("error:"),
"clippy requires a nightly version of Rust."
);
print_version_err(&current_version, &*current_date_str); print_version_err(&current_version, &*current_date_str);
eprintln!("{}{}{}", eprintln!(
"See the README (", "{}{}{}",
"https://github.com/rust-lang-nursery/rust-clippy#usage", "See the README (", "https://github.com/rust-lang-nursery/rust-clippy#usage", ") for more information."
") for more information."); );
panic!("Aborting compilation due to incompatible compiler.") panic!("Aborting compilation due to incompatible compiler.")
} }
@ -74,13 +80,15 @@ fn check_rustc_version() {
let min_date = str_to_ymd(&min_date_str).unwrap(); let min_date = str_to_ymd(&min_date_str).unwrap();
if current_date < min_date { if current_date < min_date {
eprintln!("\n{} {}", eprintln!(
Red.bold().paint("error:"), "\n{} {}",
"clippy does not support this version of rustc nightly."); Red.bold().paint("error:"),
eprintln!("> {}{}{}", "clippy does not support this version of rustc nightly."
"Use `", );
"rustup update", eprintln!(
"` or your preferred method to update Rust."); "> {}{}{}",
"Use `", "rustup update", "` or your preferred method to update Rust."
);
print_version_err(&current_version, &*current_date_str); print_version_err(&current_version, &*current_date_str);
panic!("Aborting compilation due to incompatible compiler.") panic!("Aborting compilation due to incompatible compiler.")
} }
@ -88,12 +96,8 @@ fn check_rustc_version() {
fn correct_channel(version_meta: &VersionMeta) -> bool { fn correct_channel(version_meta: &VersionMeta) -> bool {
match version_meta.channel { match version_meta.channel {
Channel::Stable | Channel::Beta => { Channel::Stable | Channel::Beta => false,
false Channel::Nightly | Channel::Dev => true,
},
Channel::Nightly | Channel::Dev => {
true
}
} }
} }
@ -101,7 +105,7 @@ fn correct_channel(version_meta: &VersionMeta) -> bool {
fn str_to_ymd(ymd: &str) -> Option<u32> { fn str_to_ymd(ymd: &str) -> Option<u32> {
let ymd: Vec<u32> = ymd.split("-").filter_map(|s| s.parse::<u32>().ok()).collect(); let ymd: Vec<u32> = ymd.split("-").filter_map(|s| s.parse::<u32>().ok()).collect();
if ymd.len() != 3 { if ymd.len() != 3 {
return None return None;
} }
let (y, m, d) = (ymd[0], ymd[1], ymd[2]); let (y, m, d) = (ymd[0], ymd[1], ymd[2]);

View file

@ -1,5 +1,5 @@
use rustc::lint::*;
use rustc::hir::*; use rustc::hir::*;
use rustc::lint::*;
use std::f64::consts as f64; use std::f64::consts as f64;
use syntax::ast::{FloatTy, Lit, LitKind}; use syntax::ast::{FloatTy, Lit, LitKind};
use syntax::symbol; use syntax::symbol;
@ -90,8 +90,7 @@ fn check_known_consts(cx: &LateContext, e: &Expr, s: &symbol::Symbol, module: &s
&format!( &format!(
"approximate value of `{}::consts::{}` found. \ "approximate value of `{}::consts::{}` found. \
Consider using it directly", Consider using it directly",
module, module, &name
&name
), ),
); );
return; return;

View file

@ -57,19 +57,19 @@ impl<'a, 'tcx> LateLintPass<'a, 'tcx> for Arithmetic {
match expr.node { match expr.node {
hir::ExprBinary(ref op, ref l, ref r) => { hir::ExprBinary(ref op, ref l, ref r) => {
match op.node { match op.node {
hir::BiAnd | hir::BiAnd
hir::BiOr | | hir::BiOr
hir::BiBitAnd | | hir::BiBitAnd
hir::BiBitOr | | hir::BiBitOr
hir::BiBitXor | | hir::BiBitXor
hir::BiShl | | hir::BiShl
hir::BiShr | | hir::BiShr
hir::BiEq | | hir::BiEq
hir::BiLt | | hir::BiLt
hir::BiLe | | hir::BiLe
hir::BiNe | | hir::BiNe
hir::BiGe | | hir::BiGe
hir::BiGt => return, | hir::BiGt => return,
_ => (), _ => (),
} }
let (l_ty, r_ty) = (cx.tables.expr_ty(l), cx.tables.expr_ty(r)); let (l_ty, r_ty) = (cx.tables.expr_ty(l), cx.tables.expr_ty(r));

View file

@ -1,10 +1,10 @@
use consts::{constant, Constant};
use rustc::hir;
use rustc::lint::*; use rustc::lint::*;
use rustc::ty; use rustc::ty;
use rustc::hir;
use syntax::ast::RangeLimits; use syntax::ast::RangeLimits;
use utils::{self, higher};
use utils::higher::Range; use utils::higher::Range;
use consts::{constant, Constant}; use utils::{self, higher};
/// **What it does:** Checks for out of bounds array indexing with a constant /// **What it does:** Checks for out of bounds array indexing with a constant
/// index. /// index.

View file

@ -95,24 +95,28 @@ impl<'a, 'tcx> LateLintPass<'a, 'tcx> for AssignOps {
MISREFACTORED_ASSIGN_OP, MISREFACTORED_ASSIGN_OP,
expr.span, expr.span,
"variable appears on both sides of an assignment operation", "variable appears on both sides of an assignment operation",
|db| if let (Some(snip_a), Some(snip_r)) = |db| {
(snippet_opt(cx, assignee.span), snippet_opt(cx, rhs_other.span)) if let (Some(snip_a), Some(snip_r)) =
{ (snippet_opt(cx, assignee.span), snippet_opt(cx, rhs_other.span))
let a = &sugg::Sugg::hir(cx, assignee, ".."); {
let r = &sugg::Sugg::hir(cx, rhs, ".."); let a = &sugg::Sugg::hir(cx, assignee, "..");
let long = format!("{} = {}", snip_a, sugg::make_binop(higher::binop(op.node), a, r)); let r = &sugg::Sugg::hir(cx, rhs, "..");
db.span_suggestion( let long =
expr.span, format!("{} = {}", snip_a, sugg::make_binop(higher::binop(op.node), a, r));
&format!("Did you mean {} = {} {} {} or {}? Consider replacing it with", db.span_suggestion(
snip_a, snip_a, op.node.as_str(), snip_r, expr.span,
long), &format!(
format!("{} {}= {}", snip_a, op.node.as_str(), snip_r) "Did you mean {} = {} {} {} or {}? Consider replacing it with",
); snip_a,
db.span_suggestion( snip_a,
expr.span, op.node.as_str(),
"or", snip_r,
long long
); ),
format!("{} {}= {}", snip_a, op.node.as_str(), snip_r),
);
db.span_suggestion(expr.span, "or", long);
}
}, },
); );
}; };
@ -189,14 +193,16 @@ impl<'a, 'tcx> LateLintPass<'a, 'tcx> for AssignOps {
ASSIGN_OP_PATTERN, ASSIGN_OP_PATTERN,
expr.span, expr.span,
"manual implementation of an assign operation", "manual implementation of an assign operation",
|db| if let (Some(snip_a), Some(snip_r)) = |db| {
(snippet_opt(cx, assignee.span), snippet_opt(cx, rhs.span)) if let (Some(snip_a), Some(snip_r)) =
{ (snippet_opt(cx, assignee.span), snippet_opt(cx, rhs.span))
db.span_suggestion( {
expr.span, db.span_suggestion(
"replace it with", expr.span,
format!("{} {}= {}", snip_a, op.node.as_str(), snip_r), "replace it with",
); format!("{} {}= {}", snip_a, op.node.as_str(), snip_r),
);
}
}, },
); );
} }
@ -205,7 +211,7 @@ impl<'a, 'tcx> LateLintPass<'a, 'tcx> for AssignOps {
let mut visitor = ExprVisitor { let mut visitor = ExprVisitor {
assignee, assignee,
counter: 0, counter: 0,
cx cx,
}; };
walk_expr(&mut visitor, e); walk_expr(&mut visitor, e);
@ -218,13 +224,13 @@ impl<'a, 'tcx> LateLintPass<'a, 'tcx> for AssignOps {
// a = b commutative_op a // a = b commutative_op a
if SpanlessEq::new(cx).ignore_fn().eq_expr(assignee, r) { if SpanlessEq::new(cx).ignore_fn().eq_expr(assignee, r) {
match op.node { match op.node {
hir::BiAdd | hir::BiAdd
hir::BiMul | | hir::BiMul
hir::BiAnd | | hir::BiAnd
hir::BiOr | | hir::BiOr
hir::BiBitXor | | hir::BiBitXor
hir::BiBitAnd | | hir::BiBitAnd
hir::BiBitOr => { | hir::BiBitOr => {
lint(assignee, l); lint(assignee, l);
}, },
_ => {}, _ => {},

View file

@ -1,13 +1,16 @@
//! checks for attributes //! checks for attributes
use reexport::*; use reexport::*;
use rustc::lint::*;
use rustc::hir::*; use rustc::hir::*;
use rustc::lint::*;
use rustc::ty::{self, TyCtxt}; use rustc::ty::{self, TyCtxt};
use semver::Version; use semver::Version;
use syntax::ast::{Attribute, AttrStyle, Lit, LitKind, MetaItemKind, NestedMetaItem, NestedMetaItemKind}; use syntax::ast::{AttrStyle, Attribute, Lit, LitKind, MetaItemKind, NestedMetaItem, NestedMetaItemKind};
use syntax::codemap::Span; use syntax::codemap::Span;
use utils::{in_macro, last_line_of_span, match_def_path, opt_def_id, paths, snippet_opt, span_lint, span_lint_and_then, without_block_comments}; use utils::{
in_macro, last_line_of_span, match_def_path, opt_def_id, paths, snippet_opt, span_lint, span_lint_and_then,
without_block_comments,
};
/// **What it does:** Checks for items annotated with `#[inline(always)]`, /// **What it does:** Checks for items annotated with `#[inline(always)]`,
/// unless the annotated function is empty or simply panics. /// unless the annotated function is empty or simply panics.
@ -118,7 +121,12 @@ pub struct AttrPass;
impl LintPass for AttrPass { impl LintPass for AttrPass {
fn get_lints(&self) -> LintArray { fn get_lints(&self) -> LintArray {
lint_array!(INLINE_ALWAYS, DEPRECATED_SEMVER, USELESS_ATTRIBUTE, EMPTY_LINE_AFTER_OUTER_ATTR) lint_array!(
INLINE_ALWAYS,
DEPRECATED_SEMVER,
USELESS_ATTRIBUTE,
EMPTY_LINE_AFTER_OUTER_ATTR
)
} }
} }
@ -170,11 +178,7 @@ impl<'a, 'tcx> LateLintPass<'a, 'tcx> for AttrPass {
"useless lint attribute", "useless lint attribute",
|db| { |db| {
sugg = sugg.replacen("#[", "#![", 1); sugg = sugg.replacen("#[", "#![", 1);
db.span_suggestion( db.span_suggestion(line_span, "if you just forgot a `!`, use", sugg);
line_span,
"if you just forgot a `!`, use",
sugg,
);
}, },
); );
} }
@ -234,10 +238,7 @@ fn is_relevant_block(tcx: TyCtxt, tables: &ty::TypeckTables, block: &Block) -> b
StmtExpr(ref expr, _) | StmtSemi(ref expr, _) => is_relevant_expr(tcx, tables, expr), StmtExpr(ref expr, _) | StmtSemi(ref expr, _) => is_relevant_expr(tcx, tables, expr),
} }
} else { } else {
block block.expr.as_ref().map_or(false, |e| is_relevant_expr(tcx, tables, e))
.expr
.as_ref()
.map_or(false, |e| is_relevant_expr(tcx, tables, e))
} }
} }

View file

@ -6,16 +6,16 @@
extern crate clippy_lints; extern crate clippy_lints;
extern crate getopts; extern crate getopts;
extern crate rustc; extern crate rustc;
extern crate rustc_codegen_utils;
extern crate rustc_driver; extern crate rustc_driver;
extern crate rustc_errors; extern crate rustc_errors;
extern crate rustc_plugin; extern crate rustc_plugin;
extern crate rustc_codegen_utils;
extern crate syntax; extern crate syntax;
use rustc_driver::{driver, Compilation, CompilerCalls, RustcDefaultCalls};
use rustc_codegen_utils::codegen_backend::CodegenBackend;
use rustc::session::{config, Session};
use rustc::session::config::{ErrorOutputType, Input}; use rustc::session::config::{ErrorOutputType, Input};
use rustc::session::{config, Session};
use rustc_codegen_utils::codegen_backend::CodegenBackend;
use rustc_driver::{driver, Compilation, CompilerCalls, RustcDefaultCalls};
use std::path::PathBuf; use std::path::PathBuf;
use std::process::Command; use std::process::Command;
use syntax::ast; use syntax::ast;
@ -43,8 +43,7 @@ impl<'a> CompilerCalls<'a> for ClippyCompilerCalls {
descriptions: &rustc_errors::registry::Registry, descriptions: &rustc_errors::registry::Registry,
output: ErrorOutputType, output: ErrorOutputType,
) -> Compilation { ) -> Compilation {
self.default self.default.early_callback(matches, sopts, cfg, descriptions, output)
.early_callback(matches, sopts, cfg, descriptions, output)
} }
fn no_input( fn no_input(
&mut self, &mut self,
@ -55,8 +54,7 @@ impl<'a> CompilerCalls<'a> for ClippyCompilerCalls {
ofile: &Option<PathBuf>, ofile: &Option<PathBuf>,
descriptions: &rustc_errors::registry::Registry, descriptions: &rustc_errors::registry::Registry,
) -> Option<(Input, Option<PathBuf>)> { ) -> Option<(Input, Option<PathBuf>)> {
self.default self.default.no_input(matches, sopts, cfg, odir, ofile, descriptions)
.no_input(matches, sopts, cfg, odir, ofile, descriptions)
} }
fn late_callback( fn late_callback(
&mut self, &mut self,
@ -118,7 +116,7 @@ impl<'a> CompilerCalls<'a> for ClippyCompilerCalls {
} }
old(state); old(state);
}); });
control.compilation_done.stop = Compilation::Stop; control.compilation_done.stop = Compilation::Stop;
} }
@ -185,15 +183,18 @@ pub fn main() {
// this check ensures that dependencies are built but not linted and the final // this check ensures that dependencies are built but not linted and the final
// crate is // crate is
// linted but not built // linted but not built
let clippy_enabled = env::var("CLIPPY_TESTS") let clippy_enabled = env::var("CLIPPY_TESTS").ok().map_or(false, |val| val == "true")
.ok()
.map_or(false, |val| val == "true")
|| orig_args.iter().any(|s| s == "--emit=dep-info,metadata"); || orig_args.iter().any(|s| s == "--emit=dep-info,metadata");
if clippy_enabled { if clippy_enabled {
args.extend_from_slice(&["--cfg".to_owned(), r#"feature="cargo-clippy""#.to_owned()]); args.extend_from_slice(&["--cfg".to_owned(), r#"feature="cargo-clippy""#.to_owned()]);
if let Ok(extra_args) = env::var("CLIPPY_ARGS") { if let Ok(extra_args) = env::var("CLIPPY_ARGS") {
args.extend(extra_args.split("__CLIPPY_HACKERY__").filter(|s| !s.is_empty()).map(str::to_owned)); args.extend(
extra_args
.split("__CLIPPY_HACKERY__")
.filter(|s| !s.is_empty())
.map(str::to_owned),
);
} }
} }

View file

@ -15,7 +15,9 @@ pub fn plugin_registrar(reg: &mut Registry) {
reg.sess.lint_store.with_read_lock(|lint_store| { reg.sess.lint_store.with_read_lock(|lint_store| {
for (lint, _, _) in lint_store.get_lint_groups() { for (lint, _, _) in lint_store.get_lint_groups() {
reg.sess reg.sess
.struct_warn("the clippy plugin is being deprecated, please use cargo clippy or rls with the clippy feature") .struct_warn(
"the clippy plugin is being deprecated, please use cargo clippy or rls with the clippy feature",
)
.emit(); .emit();
if lint == "clippy" { if lint == "clippy" {
// cargo clippy run on a crate that also uses the plugin // cargo clippy run on a crate that also uses the plugin

View file

@ -3,8 +3,8 @@
extern crate compiletest_rs as compiletest; extern crate compiletest_rs as compiletest;
extern crate test; extern crate test;
use std::path::{Path, PathBuf};
use std::env::{set_var, var}; use std::env::{set_var, var};
use std::path::{Path, PathBuf};
fn clippy_driver_path() -> PathBuf { fn clippy_driver_path() -> PathBuf {
if let Some(path) = option_env!("CLIPPY_DRIVER_PATH") { if let Some(path) = option_env!("CLIPPY_DRIVER_PATH") {
@ -43,10 +43,7 @@ fn config(dir: &'static str, mode: &'static str) -> compiletest::Config {
config.run_lib_path = rustc_lib_path(); config.run_lib_path = rustc_lib_path();
config.compile_lib_path = rustc_lib_path(); config.compile_lib_path = rustc_lib_path();
} }
config.target_rustcflags = Some(format!( config.target_rustcflags = Some(format!("-L {0} -L {0}/deps -Dwarnings", host_libs().display()));
"-L {0} -L {0}/deps -Dwarnings",
host_libs().display()
));
config.mode = cfg_mode; config.mode = cfg_mode;
config.build_base = if rustc_test_suite().is_some() { config.build_base = if rustc_test_suite().is_some() {

View file

@ -7,10 +7,7 @@ fn check_that_clippy_lints_has_the_same_version_as_clippy() {
let clippy_meta = cargo_metadata::metadata(None).expect("could not obtain cargo metadata"); let clippy_meta = cargo_metadata::metadata(None).expect("could not obtain cargo metadata");
std::env::set_current_dir(std::env::current_dir().unwrap().join("clippy_lints")).unwrap(); std::env::set_current_dir(std::env::current_dir().unwrap().join("clippy_lints")).unwrap();
let clippy_lints_meta = cargo_metadata::metadata(None).expect("could not obtain cargo metadata"); let clippy_lints_meta = cargo_metadata::metadata(None).expect("could not obtain cargo metadata");
assert_eq!( assert_eq!(clippy_lints_meta.packages[0].version, clippy_meta.packages[0].version);
clippy_lints_meta.packages[0].version,
clippy_meta.packages[0].version
);
for package in &clippy_meta.packages[0].dependencies { for package in &clippy_meta.packages[0].dependencies {
if package.name == "clippy_lints" { if package.name == "clippy_lints" {
assert_eq!( assert_eq!(

View file

@ -7,9 +7,7 @@ fn test_lines_without_block_comments() {
println!("result: {:?}", result); println!("result: {:?}", result);
assert!(result.is_empty()); assert!(result.is_empty());
let result = without_block_comments( let result = without_block_comments(vec!["", "/*", "", "*/", "#[crate_type = \"lib\"]", "/*", "", "*/", ""]);
vec!["", "/*", "", "*/", "#[crate_type = \"lib\"]", "/*", "", "*/", ""]
);
assert_eq!(result, vec!["", "#[crate_type = \"lib\"]", ""]); assert_eq!(result, vec!["", "#[crate_type = \"lib\"]", ""]);
let result = without_block_comments(vec!["/* rust", "", "*/"]); let result = without_block_comments(vec!["/* rust", "", "*/"]);
@ -18,7 +16,7 @@ fn test_lines_without_block_comments() {
let result = without_block_comments(vec!["/* one-line comment */"]); let result = without_block_comments(vec!["/* one-line comment */"]);
assert!(result.is_empty()); assert!(result.is_empty());
let result = without_block_comments(vec!["/* nested", "/* multi-line", "comment", "*/", "test", "*/"]); let result = without_block_comments(vec!["/* nested", "/* multi-line", "comment", "*/", "test", "*/"]);
assert!(result.is_empty()); assert!(result.is_empty());
let result = without_block_comments(vec!["/* nested /* inline /* comment */ test */ */"]); let result = without_block_comments(vec!["/* nested /* inline /* comment */ test */ */"]);