Auto merge of #28429 - wesleywiser:split_up_lints, r=alexcrichton

This breaks out some of the lints defined in `librustc_lint/builtin.rs` into two new modules: `unused` for the `UNUSED_*` lints and `bad_style` for the various style related lints as suggested in #22206. `builtin.rs` could probably get broken up more but this is a start.
This commit is contained in:
bors 2015-09-20 19:48:12 +00:00
commit 2c06bb96ea
4 changed files with 859 additions and 799 deletions

View file

@ -0,0 +1,372 @@
// Copyright 2015 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
use middle::def;
use middle::def_id::DefId;
use middle::ty;
use lint::{LateContext, LintContext, LintArray};
use lint::{LintPass, LateLintPass};
use syntax::ast;
use syntax::attr::{self, AttrMetaMethods};
use syntax::codemap::Span;
use rustc_front::hir;
use rustc_front::visit::FnKind;
#[derive(PartialEq)]
pub enum MethodLateContext {
TraitDefaultImpl,
TraitImpl,
PlainImpl
}
pub fn method_context(cx: &LateContext, id: ast::NodeId, span: Span) -> MethodLateContext {
match cx.tcx.impl_or_trait_items.borrow().get(&DefId::local(id)) {
None => cx.sess().span_bug(span, "missing method descriptor?!"),
Some(item) => match item.container() {
ty::TraitContainer(..) => MethodLateContext::TraitDefaultImpl,
ty::ImplContainer(cid) => {
match cx.tcx.impl_trait_ref(cid) {
Some(_) => MethodLateContext::TraitImpl,
None => MethodLateContext::PlainImpl
}
}
}
}
}
declare_lint! {
pub NON_CAMEL_CASE_TYPES,
Warn,
"types, variants, traits and type parameters should have camel case names"
}
#[derive(Copy, Clone)]
pub struct NonCamelCaseTypes;
impl NonCamelCaseTypes {
fn check_case(&self, cx: &LateContext, sort: &str, ident: ast::Ident, span: Span) {
fn is_camel_case(ident: ast::Ident) -> bool {
let ident = ident.name.as_str();
if ident.is_empty() {
return true;
}
let ident = ident.trim_matches('_');
// start with a non-lowercase letter rather than non-uppercase
// ones (some scripts don't have a concept of upper/lowercase)
!ident.is_empty() && !ident.char_at(0).is_lowercase() && !ident.contains('_')
}
fn to_camel_case(s: &str) -> String {
s.split('_').flat_map(|word| word.chars().enumerate().map(|(i, c)|
if i == 0 {
c.to_uppercase().collect::<String>()
} else {
c.to_lowercase().collect()
}
)).collect::<Vec<_>>().concat()
}
let s = ident.name.as_str();
if !is_camel_case(ident) {
let c = to_camel_case(&s);
let m = if c.is_empty() {
format!("{} `{}` should have a camel case name such as `CamelCase`", sort, s)
} else {
format!("{} `{}` should have a camel case name such as `{}`", sort, s, c)
};
cx.span_lint(NON_CAMEL_CASE_TYPES, span, &m[..]);
}
}
}
impl LintPass for NonCamelCaseTypes {
fn get_lints(&self) -> LintArray {
lint_array!(NON_CAMEL_CASE_TYPES)
}
}
impl LateLintPass for NonCamelCaseTypes {
fn check_item(&mut self, cx: &LateContext, it: &hir::Item) {
let extern_repr_count = it.attrs.iter().filter(|attr| {
attr::find_repr_attrs(cx.tcx.sess.diagnostic(), attr).iter()
.any(|r| r == &attr::ReprExtern)
}).count();
let has_extern_repr = extern_repr_count > 0;
if has_extern_repr {
return;
}
match it.node {
hir::ItemTy(..) | hir::ItemStruct(..) => {
self.check_case(cx, "type", it.ident, it.span)
}
hir::ItemTrait(..) => {
self.check_case(cx, "trait", it.ident, it.span)
}
hir::ItemEnum(ref enum_definition, _) => {
if has_extern_repr {
return;
}
self.check_case(cx, "type", it.ident, it.span);
for variant in &enum_definition.variants {
self.check_case(cx, "variant", variant.node.name, variant.span);
}
}
_ => ()
}
}
fn check_generics(&mut self, cx: &LateContext, it: &hir::Generics) {
for gen in it.ty_params.iter() {
self.check_case(cx, "type parameter", gen.ident, gen.span);
}
}
}
declare_lint! {
pub NON_SNAKE_CASE,
Warn,
"methods, functions, lifetime parameters and modules should have snake case names"
}
#[derive(Copy, Clone)]
pub struct NonSnakeCase;
impl NonSnakeCase {
fn to_snake_case(mut str: &str) -> String {
let mut words = vec![];
// Preserve leading underscores
str = str.trim_left_matches(|c: char| {
if c == '_' {
words.push(String::new());
true
} else {
false
}
});
for s in str.split('_') {
let mut last_upper = false;
let mut buf = String::new();
if s.is_empty() {
continue;
}
for ch in s.chars() {
if !buf.is_empty() && buf != "'"
&& ch.is_uppercase()
&& !last_upper {
words.push(buf);
buf = String::new();
}
last_upper = ch.is_uppercase();
buf.extend(ch.to_lowercase());
}
words.push(buf);
}
words.join("_")
}
fn check_snake_case(&self, cx: &LateContext, sort: &str, name: &str, span: Option<Span>) {
fn is_snake_case(ident: &str) -> bool {
if ident.is_empty() {
return true;
}
let ident = ident.trim_left_matches('\'');
let ident = ident.trim_matches('_');
let mut allow_underscore = true;
ident.chars().all(|c| {
allow_underscore = match c {
'_' if !allow_underscore => return false,
'_' => false,
// It would be more obvious to use `c.is_lowercase()`,
// but some characters do not have a lowercase form
c if !c.is_uppercase() => true,
_ => return false,
};
true
})
}
if !is_snake_case(name) {
let sc = NonSnakeCase::to_snake_case(name);
let msg = if sc != name {
format!("{} `{}` should have a snake case name such as `{}`",
sort, name, sc)
} else {
format!("{} `{}` should have a snake case name",
sort, name)
};
match span {
Some(span) => cx.span_lint(NON_SNAKE_CASE, span, &msg),
None => cx.lint(NON_SNAKE_CASE, &msg),
}
}
}
}
impl LintPass for NonSnakeCase {
fn get_lints(&self) -> LintArray {
lint_array!(NON_SNAKE_CASE)
}
}
impl LateLintPass for NonSnakeCase {
fn check_crate(&mut self, cx: &LateContext, cr: &hir::Crate) {
let attr_crate_name = cr.attrs.iter().find(|at| at.check_name("crate_name"))
.and_then(|at| at.value_str().map(|s| (at, s)));
if let Some(ref name) = cx.tcx.sess.opts.crate_name {
self.check_snake_case(cx, "crate", name, None);
} else if let Some((attr, ref name)) = attr_crate_name {
self.check_snake_case(cx, "crate", name, Some(attr.span));
}
}
fn check_fn(&mut self, cx: &LateContext,
fk: FnKind, _: &hir::FnDecl,
_: &hir::Block, span: Span, id: ast::NodeId) {
match fk {
FnKind::Method(ident, _, _) => match method_context(cx, id, span) {
MethodLateContext::PlainImpl => {
self.check_snake_case(cx, "method", &ident.name.as_str(), Some(span))
},
MethodLateContext::TraitDefaultImpl => {
self.check_snake_case(cx, "trait method", &ident.name.as_str(), Some(span))
},
_ => (),
},
FnKind::ItemFn(ident, _, _, _, _, _) => {
self.check_snake_case(cx, "function", &ident.name.as_str(), Some(span))
},
_ => (),
}
}
fn check_item(&mut self, cx: &LateContext, it: &hir::Item) {
if let hir::ItemMod(_) = it.node {
self.check_snake_case(cx, "module", &it.ident.name.as_str(), Some(it.span));
}
}
fn check_trait_item(&mut self, cx: &LateContext, trait_item: &hir::TraitItem) {
if let hir::MethodTraitItem(_, None) = trait_item.node {
self.check_snake_case(cx, "trait method", &trait_item.ident.name.as_str(),
Some(trait_item.span));
}
}
fn check_lifetime_def(&mut self, cx: &LateContext, t: &hir::LifetimeDef) {
self.check_snake_case(cx, "lifetime", &t.lifetime.name.as_str(),
Some(t.lifetime.span));
}
fn check_pat(&mut self, cx: &LateContext, p: &hir::Pat) {
if let &hir::PatIdent(_, ref path1, _) = &p.node {
let def = cx.tcx.def_map.borrow().get(&p.id).map(|d| d.full_def());
if let Some(def::DefLocal(_)) = def {
self.check_snake_case(cx, "variable", &path1.node.name.as_str(), Some(p.span));
}
}
}
fn check_struct_def(&mut self, cx: &LateContext, s: &hir::StructDef,
_: ast::Ident, _: &hir::Generics, _: ast::NodeId) {
for sf in &s.fields {
if let hir::StructField_ { kind: hir::NamedField(ident, _), .. } = sf.node {
self.check_snake_case(cx, "structure field", &ident.name.as_str(),
Some(sf.span));
}
}
}
}
declare_lint! {
pub NON_UPPER_CASE_GLOBALS,
Warn,
"static constants should have uppercase identifiers"
}
#[derive(Copy, Clone)]
pub struct NonUpperCaseGlobals;
impl NonUpperCaseGlobals {
fn check_upper_case(cx: &LateContext, sort: &str, ident: ast::Ident, span: Span) {
let s = ident.name.as_str();
if s.chars().any(|c| c.is_lowercase()) {
let uc = NonSnakeCase::to_snake_case(&s).to_uppercase();
if uc != &s[..] {
cx.span_lint(NON_UPPER_CASE_GLOBALS, span,
&format!("{} `{}` should have an upper case name such as `{}`",
sort, s, uc));
} else {
cx.span_lint(NON_UPPER_CASE_GLOBALS, span,
&format!("{} `{}` should have an upper case name",
sort, s));
}
}
}
}
impl LintPass for NonUpperCaseGlobals {
fn get_lints(&self) -> LintArray {
lint_array!(NON_UPPER_CASE_GLOBALS)
}
}
impl LateLintPass for NonUpperCaseGlobals {
fn check_item(&mut self, cx: &LateContext, it: &hir::Item) {
match it.node {
// only check static constants
hir::ItemStatic(_, hir::MutImmutable, _) => {
NonUpperCaseGlobals::check_upper_case(cx, "static constant", it.ident, it.span);
}
hir::ItemConst(..) => {
NonUpperCaseGlobals::check_upper_case(cx, "constant", it.ident, it.span);
}
_ => {}
}
}
fn check_trait_item(&mut self, cx: &LateContext, ti: &hir::TraitItem) {
match ti.node {
hir::ConstTraitItem(..) => {
NonUpperCaseGlobals::check_upper_case(cx, "associated constant",
ti.ident, ti.span);
}
_ => {}
}
}
fn check_impl_item(&mut self, cx: &LateContext, ii: &hir::ImplItem) {
match ii.node {
hir::ConstImplItem(..) => {
NonUpperCaseGlobals::check_upper_case(cx, "associated constant",
ii.ident, ii.span);
}
_ => {}
}
}
fn check_pat(&mut self, cx: &LateContext, p: &hir::Pat) {
// Lint for constants that look like binding identifiers (#7526)
match (&p.node, cx.tcx.def_map.borrow().get(&p.id).map(|d| d.full_def())) {
(&hir::PatIdent(_, ref path1, _), Some(def::DefConst(..))) => {
NonUpperCaseGlobals::check_upper_case(cx, "constant in pattern",
path1.node, p.span);
}
_ => {}
}
}
}

View file

@ -28,8 +28,8 @@
//! Use the former for unit-like structs and the latter for structs with
//! a `pub fn new()`.
use metadata::{csearch, decoder};
use middle::{cfg, def, infer, pat_util, stability, traits};
use metadata::decoder;
use middle::{cfg, def, infer, stability, traits};
use middle::def_id::DefId;
use middle::subst::Substs;
use middle::ty::{self, Ty};
@ -37,26 +37,26 @@ use middle::ty::adjustment;
use middle::const_eval::{eval_const_expr_partial, ConstVal};
use middle::const_eval::EvalHint::ExprTypeChecked;
use rustc::front::map as hir_map;
use util::nodemap::{FnvHashMap, FnvHashSet, NodeSet};
use lint::{Level, LateContext, EarlyContext, LintContext, LintArray, Lint};
use lint::{LintPass, EarlyLintPass, LateLintPass};
use util::nodemap::{FnvHashSet, NodeSet};
use lint::{Level, LateContext, LintContext, LintArray, Lint};
use lint::{LintPass, LateLintPass};
use std::collections::HashSet;
use std::collections::hash_map::Entry::{Occupied, Vacant};
use std::{cmp, slice};
use std::cmp;
use std::{i8, i16, i32, i64, u8, u16, u32, u64, f32, f64};
use syntax::{abi, ast};
use syntax::attr::{self, AttrMetaMethods};
use syntax::codemap::{self, Span};
use syntax::feature_gate::{KNOWN_ATTRIBUTES, AttributeType, emit_feature_err, GateIssue};
use syntax::feature_gate::{emit_feature_err, GateIssue};
use syntax::ast::{TyIs, TyUs, TyI8, TyU8, TyI16, TyU16, TyI32, TyU32, TyI64, TyU64};
use syntax::ptr::P;
use rustc_front::hir;
use rustc_front::visit::{self, FnKind, Visitor};
use rustc_front::util::is_shift_binop;
use bad_style::{MethodLateContext, method_context};
// hardwired lints from librustc
pub use lint::builtin::*;
@ -881,652 +881,6 @@ impl LateLintPass for RawPointerDerive {
}
}
declare_lint! {
UNUSED_ATTRIBUTES,
Warn,
"detects attributes that were not used by the compiler"
}
#[derive(Copy, Clone)]
pub struct UnusedAttributes;
impl LintPass for UnusedAttributes {
fn get_lints(&self) -> LintArray {
lint_array!(UNUSED_ATTRIBUTES)
}
}
impl LateLintPass for UnusedAttributes {
fn check_attribute(&mut self, cx: &LateContext, attr: &ast::Attribute) {
// Note that check_name() marks the attribute as used if it matches.
for &(ref name, ty, _) in KNOWN_ATTRIBUTES {
match ty {
AttributeType::Whitelisted if attr.check_name(name) => {
break;
},
_ => ()
}
}
let plugin_attributes = cx.sess().plugin_attributes.borrow_mut();
for &(ref name, ty) in plugin_attributes.iter() {
if ty == AttributeType::Whitelisted && attr.check_name(&*name) {
break;
}
}
if !attr::is_used(attr) {
cx.span_lint(UNUSED_ATTRIBUTES, attr.span, "unused attribute");
// Is it a builtin attribute that must be used at the crate level?
let known_crate = KNOWN_ATTRIBUTES.iter().find(|&&(name, ty, _)| {
attr.name() == name &&
ty == AttributeType::CrateLevel
}).is_some();
// Has a plugin registered this attribute as one which must be used at
// the crate level?
let plugin_crate = plugin_attributes.iter()
.find(|&&(ref x, t)| {
&*attr.name() == &*x &&
AttributeType::CrateLevel == t
}).is_some();
if known_crate || plugin_crate {
let msg = match attr.node.style {
ast::AttrOuter => "crate-level attribute should be an inner \
attribute: add an exclamation mark: #![foo]",
ast::AttrInner => "crate-level attribute should be in the \
root module",
};
cx.span_lint(UNUSED_ATTRIBUTES, attr.span, msg);
}
}
}
}
declare_lint! {
pub PATH_STATEMENTS,
Warn,
"path statements with no effect"
}
#[derive(Copy, Clone)]
pub struct PathStatements;
impl LintPass for PathStatements {
fn get_lints(&self) -> LintArray {
lint_array!(PATH_STATEMENTS)
}
}
impl LateLintPass for PathStatements {
fn check_stmt(&mut self, cx: &LateContext, s: &hir::Stmt) {
match s.node {
hir::StmtSemi(ref expr, _) => {
match expr.node {
hir::ExprPath(..) => cx.span_lint(PATH_STATEMENTS, s.span,
"path statement with no effect"),
_ => ()
}
}
_ => ()
}
}
}
declare_lint! {
pub UNUSED_MUST_USE,
Warn,
"unused result of a type flagged as #[must_use]"
}
declare_lint! {
pub UNUSED_RESULTS,
Allow,
"unused result of an expression in a statement"
}
#[derive(Copy, Clone)]
pub struct UnusedResults;
impl LintPass for UnusedResults {
fn get_lints(&self) -> LintArray {
lint_array!(UNUSED_MUST_USE, UNUSED_RESULTS)
}
}
impl LateLintPass for UnusedResults {
fn check_stmt(&mut self, cx: &LateContext, s: &hir::Stmt) {
let expr = match s.node {
hir::StmtSemi(ref expr, _) => &**expr,
_ => return
};
if let hir::ExprRet(..) = expr.node {
return;
}
let t = cx.tcx.expr_ty(&expr);
let warned = match t.sty {
ty::TyTuple(ref tys) if tys.is_empty() => return,
ty::TyBool => return,
ty::TyStruct(def, _) |
ty::TyEnum(def, _) => {
if def.did.is_local() {
if let hir_map::NodeItem(it) = cx.tcx.map.get(def.did.node) {
check_must_use(cx, &it.attrs, s.span)
} else {
false
}
} else {
let attrs = csearch::get_item_attrs(&cx.sess().cstore, def.did);
check_must_use(cx, &attrs[..], s.span)
}
}
_ => false,
};
if !warned {
cx.span_lint(UNUSED_RESULTS, s.span, "unused result");
}
fn check_must_use(cx: &LateContext, attrs: &[ast::Attribute], sp: Span) -> bool {
for attr in attrs {
if attr.check_name("must_use") {
let mut msg = "unused result which must be used".to_string();
// check for #[must_use="..."]
match attr.value_str() {
None => {}
Some(s) => {
msg.push_str(": ");
msg.push_str(&s);
}
}
cx.span_lint(UNUSED_MUST_USE, sp, &msg);
return true;
}
}
false
}
}
}
declare_lint! {
pub NON_CAMEL_CASE_TYPES,
Warn,
"types, variants, traits and type parameters should have camel case names"
}
#[derive(Copy, Clone)]
pub struct NonCamelCaseTypes;
impl NonCamelCaseTypes {
fn check_case(&self, cx: &LateContext, sort: &str, ident: ast::Ident, span: Span) {
fn is_camel_case(ident: ast::Ident) -> bool {
let ident = ident.name.as_str();
if ident.is_empty() {
return true;
}
let ident = ident.trim_matches('_');
// start with a non-lowercase letter rather than non-uppercase
// ones (some scripts don't have a concept of upper/lowercase)
!ident.is_empty() && !ident.char_at(0).is_lowercase() && !ident.contains('_')
}
fn to_camel_case(s: &str) -> String {
s.split('_').flat_map(|word| word.chars().enumerate().map(|(i, c)|
if i == 0 {
c.to_uppercase().collect::<String>()
} else {
c.to_lowercase().collect()
}
)).collect::<Vec<_>>().concat()
}
let s = ident.name.as_str();
if !is_camel_case(ident) {
let c = to_camel_case(&s);
let m = if c.is_empty() {
format!("{} `{}` should have a camel case name such as `CamelCase`", sort, s)
} else {
format!("{} `{}` should have a camel case name such as `{}`", sort, s, c)
};
cx.span_lint(NON_CAMEL_CASE_TYPES, span, &m[..]);
}
}
}
impl LintPass for NonCamelCaseTypes {
fn get_lints(&self) -> LintArray {
lint_array!(NON_CAMEL_CASE_TYPES)
}
}
impl LateLintPass for NonCamelCaseTypes {
fn check_item(&mut self, cx: &LateContext, it: &hir::Item) {
let extern_repr_count = it.attrs.iter().filter(|attr| {
attr::find_repr_attrs(cx.tcx.sess.diagnostic(), attr).iter()
.any(|r| r == &attr::ReprExtern)
}).count();
let has_extern_repr = extern_repr_count > 0;
if has_extern_repr {
return;
}
match it.node {
hir::ItemTy(..) | hir::ItemStruct(..) => {
self.check_case(cx, "type", it.ident, it.span)
}
hir::ItemTrait(..) => {
self.check_case(cx, "trait", it.ident, it.span)
}
hir::ItemEnum(ref enum_definition, _) => {
if has_extern_repr {
return;
}
self.check_case(cx, "type", it.ident, it.span);
for variant in &enum_definition.variants {
self.check_case(cx, "variant", variant.node.name, variant.span);
}
}
_ => ()
}
}
fn check_generics(&mut self, cx: &LateContext, it: &hir::Generics) {
for gen in it.ty_params.iter() {
self.check_case(cx, "type parameter", gen.ident, gen.span);
}
}
}
#[derive(PartialEq)]
enum MethodLateContext {
TraitDefaultImpl,
TraitImpl,
PlainImpl
}
fn method_context(cx: &LateContext, id: ast::NodeId, span: Span) -> MethodLateContext {
match cx.tcx.impl_or_trait_items.borrow().get(&DefId::local(id)) {
None => cx.sess().span_bug(span, "missing method descriptor?!"),
Some(item) => match item.container() {
ty::TraitContainer(..) => MethodLateContext::TraitDefaultImpl,
ty::ImplContainer(cid) => {
match cx.tcx.impl_trait_ref(cid) {
Some(_) => MethodLateContext::TraitImpl,
None => MethodLateContext::PlainImpl
}
}
}
}
}
declare_lint! {
pub NON_SNAKE_CASE,
Warn,
"methods, functions, lifetime parameters and modules should have snake case names"
}
#[derive(Copy, Clone)]
pub struct NonSnakeCase;
impl NonSnakeCase {
fn to_snake_case(mut str: &str) -> String {
let mut words = vec![];
// Preserve leading underscores
str = str.trim_left_matches(|c: char| {
if c == '_' {
words.push(String::new());
true
} else {
false
}
});
for s in str.split('_') {
let mut last_upper = false;
let mut buf = String::new();
if s.is_empty() {
continue;
}
for ch in s.chars() {
if !buf.is_empty() && buf != "'"
&& ch.is_uppercase()
&& !last_upper {
words.push(buf);
buf = String::new();
}
last_upper = ch.is_uppercase();
buf.extend(ch.to_lowercase());
}
words.push(buf);
}
words.join("_")
}
fn check_snake_case(&self, cx: &LateContext, sort: &str, name: &str, span: Option<Span>) {
fn is_snake_case(ident: &str) -> bool {
if ident.is_empty() {
return true;
}
let ident = ident.trim_left_matches('\'');
let ident = ident.trim_matches('_');
let mut allow_underscore = true;
ident.chars().all(|c| {
allow_underscore = match c {
'_' if !allow_underscore => return false,
'_' => false,
// It would be more obvious to use `c.is_lowercase()`,
// but some characters do not have a lowercase form
c if !c.is_uppercase() => true,
_ => return false,
};
true
})
}
if !is_snake_case(name) {
let sc = NonSnakeCase::to_snake_case(name);
let msg = if sc != name {
format!("{} `{}` should have a snake case name such as `{}`",
sort, name, sc)
} else {
format!("{} `{}` should have a snake case name",
sort, name)
};
match span {
Some(span) => cx.span_lint(NON_SNAKE_CASE, span, &msg),
None => cx.lint(NON_SNAKE_CASE, &msg),
}
}
}
}
impl LintPass for NonSnakeCase {
fn get_lints(&self) -> LintArray {
lint_array!(NON_SNAKE_CASE)
}
}
impl LateLintPass for NonSnakeCase {
fn check_crate(&mut self, cx: &LateContext, cr: &hir::Crate) {
let attr_crate_name = cr.attrs.iter().find(|at| at.check_name("crate_name"))
.and_then(|at| at.value_str().map(|s| (at, s)));
if let Some(ref name) = cx.tcx.sess.opts.crate_name {
self.check_snake_case(cx, "crate", name, None);
} else if let Some((attr, ref name)) = attr_crate_name {
self.check_snake_case(cx, "crate", name, Some(attr.span));
}
}
fn check_fn(&mut self, cx: &LateContext,
fk: FnKind, _: &hir::FnDecl,
_: &hir::Block, span: Span, id: ast::NodeId) {
match fk {
FnKind::Method(ident, _, _) => match method_context(cx, id, span) {
MethodLateContext::PlainImpl => {
self.check_snake_case(cx, "method", &ident.name.as_str(), Some(span))
},
MethodLateContext::TraitDefaultImpl => {
self.check_snake_case(cx, "trait method", &ident.name.as_str(), Some(span))
},
_ => (),
},
FnKind::ItemFn(ident, _, _, _, _, _) => {
self.check_snake_case(cx, "function", &ident.name.as_str(), Some(span))
},
_ => (),
}
}
fn check_item(&mut self, cx: &LateContext, it: &hir::Item) {
if let hir::ItemMod(_) = it.node {
self.check_snake_case(cx, "module", &it.ident.name.as_str(), Some(it.span));
}
}
fn check_trait_item(&mut self, cx: &LateContext, trait_item: &hir::TraitItem) {
if let hir::MethodTraitItem(_, None) = trait_item.node {
self.check_snake_case(cx, "trait method", &trait_item.ident.name.as_str(),
Some(trait_item.span));
}
}
fn check_lifetime_def(&mut self, cx: &LateContext, t: &hir::LifetimeDef) {
self.check_snake_case(cx, "lifetime", &t.lifetime.name.as_str(),
Some(t.lifetime.span));
}
fn check_pat(&mut self, cx: &LateContext, p: &hir::Pat) {
if let &hir::PatIdent(_, ref path1, _) = &p.node {
let def = cx.tcx.def_map.borrow().get(&p.id).map(|d| d.full_def());
if let Some(def::DefLocal(_)) = def {
self.check_snake_case(cx, "variable", &path1.node.name.as_str(), Some(p.span));
}
}
}
fn check_struct_def(&mut self, cx: &LateContext, s: &hir::StructDef,
_: ast::Ident, _: &hir::Generics, _: ast::NodeId) {
for sf in &s.fields {
if let hir::StructField_ { kind: hir::NamedField(ident, _), .. } = sf.node {
self.check_snake_case(cx, "structure field", &ident.name.as_str(),
Some(sf.span));
}
}
}
}
declare_lint! {
pub NON_UPPER_CASE_GLOBALS,
Warn,
"static constants should have uppercase identifiers"
}
#[derive(Copy, Clone)]
pub struct NonUpperCaseGlobals;
impl NonUpperCaseGlobals {
fn check_upper_case(cx: &LateContext, sort: &str, ident: ast::Ident, span: Span) {
let s = ident.name.as_str();
if s.chars().any(|c| c.is_lowercase()) {
let uc = NonSnakeCase::to_snake_case(&s).to_uppercase();
if uc != &s[..] {
cx.span_lint(NON_UPPER_CASE_GLOBALS, span,
&format!("{} `{}` should have an upper case name such as `{}`",
sort, s, uc));
} else {
cx.span_lint(NON_UPPER_CASE_GLOBALS, span,
&format!("{} `{}` should have an upper case name",
sort, s));
}
}
}
}
impl LintPass for NonUpperCaseGlobals {
fn get_lints(&self) -> LintArray {
lint_array!(NON_UPPER_CASE_GLOBALS)
}
}
impl LateLintPass for NonUpperCaseGlobals {
fn check_item(&mut self, cx: &LateContext, it: &hir::Item) {
match it.node {
// only check static constants
hir::ItemStatic(_, hir::MutImmutable, _) => {
NonUpperCaseGlobals::check_upper_case(cx, "static constant", it.ident, it.span);
}
hir::ItemConst(..) => {
NonUpperCaseGlobals::check_upper_case(cx, "constant", it.ident, it.span);
}
_ => {}
}
}
fn check_trait_item(&mut self, cx: &LateContext, ti: &hir::TraitItem) {
match ti.node {
hir::ConstTraitItem(..) => {
NonUpperCaseGlobals::check_upper_case(cx, "associated constant",
ti.ident, ti.span);
}
_ => {}
}
}
fn check_impl_item(&mut self, cx: &LateContext, ii: &hir::ImplItem) {
match ii.node {
hir::ConstImplItem(..) => {
NonUpperCaseGlobals::check_upper_case(cx, "associated constant",
ii.ident, ii.span);
}
_ => {}
}
}
fn check_pat(&mut self, cx: &LateContext, p: &hir::Pat) {
// Lint for constants that look like binding identifiers (#7526)
match (&p.node, cx.tcx.def_map.borrow().get(&p.id).map(|d| d.full_def())) {
(&hir::PatIdent(_, ref path1, _), Some(def::DefConst(..))) => {
NonUpperCaseGlobals::check_upper_case(cx, "constant in pattern",
path1.node, p.span);
}
_ => {}
}
}
}
declare_lint! {
UNUSED_PARENS,
Warn,
"`if`, `match`, `while` and `return` do not need parentheses"
}
#[derive(Copy, Clone)]
pub struct UnusedParens;
impl UnusedParens {
fn check_unused_parens_core(&self, cx: &EarlyContext, value: &ast::Expr, msg: &str,
struct_lit_needs_parens: bool) {
if let ast::ExprParen(ref inner) = value.node {
let necessary = struct_lit_needs_parens && contains_exterior_struct_lit(&**inner);
if !necessary {
cx.span_lint(UNUSED_PARENS, value.span,
&format!("unnecessary parentheses around {}", msg))
}
}
/// Expressions that syntactically contain an "exterior" struct
/// literal i.e. not surrounded by any parens or other
/// delimiters, e.g. `X { y: 1 }`, `X { y: 1 }.method()`, `foo
/// == X { y: 1 }` and `X { y: 1 } == foo` all do, but `(X {
/// y: 1 }) == foo` does not.
fn contains_exterior_struct_lit(value: &ast::Expr) -> bool {
match value.node {
ast::ExprStruct(..) => true,
ast::ExprAssign(ref lhs, ref rhs) |
ast::ExprAssignOp(_, ref lhs, ref rhs) |
ast::ExprBinary(_, ref lhs, ref rhs) => {
// X { y: 1 } + X { y: 2 }
contains_exterior_struct_lit(&**lhs) ||
contains_exterior_struct_lit(&**rhs)
}
ast::ExprUnary(_, ref x) |
ast::ExprCast(ref x, _) |
ast::ExprField(ref x, _) |
ast::ExprTupField(ref x, _) |
ast::ExprIndex(ref x, _) => {
// &X { y: 1 }, X { y: 1 }.y
contains_exterior_struct_lit(&**x)
}
ast::ExprMethodCall(_, _, ref exprs) => {
// X { y: 1 }.bar(...)
contains_exterior_struct_lit(&*exprs[0])
}
_ => false
}
}
}
}
impl LintPass for UnusedParens {
fn get_lints(&self) -> LintArray {
lint_array!(UNUSED_PARENS)
}
}
impl EarlyLintPass for UnusedParens {
fn check_expr(&mut self, cx: &EarlyContext, e: &ast::Expr) {
let (value, msg, struct_lit_needs_parens) = match e.node {
ast::ExprIf(ref cond, _, _) => (cond, "`if` condition", true),
ast::ExprWhile(ref cond, _, _) => (cond, "`while` condition", true),
ast::ExprMatch(ref head, _, source) => match source {
ast::MatchSource::Normal => (head, "`match` head expression", true),
ast::MatchSource::IfLetDesugar { .. } => (head, "`if let` head expression", true),
ast::MatchSource::WhileLetDesugar => (head, "`while let` head expression", true),
ast::MatchSource::ForLoopDesugar => (head, "`for` head expression", true),
},
ast::ExprRet(Some(ref value)) => (value, "`return` value", false),
ast::ExprAssign(_, ref value) => (value, "assigned value", false),
ast::ExprAssignOp(_, _, ref value) => (value, "assigned value", false),
_ => return
};
self.check_unused_parens_core(cx, &**value, msg, struct_lit_needs_parens);
}
fn check_stmt(&mut self, cx: &EarlyContext, s: &ast::Stmt) {
let (value, msg) = match s.node {
ast::StmtDecl(ref decl, _) => match decl.node {
ast::DeclLocal(ref local) => match local.init {
Some(ref value) => (value, "assigned value"),
None => return
},
_ => return
},
_ => return
};
self.check_unused_parens_core(cx, &**value, msg, false);
}
}
declare_lint! {
UNUSED_IMPORT_BRACES,
Allow,
"unnecessary braces around an imported item"
}
#[derive(Copy, Clone)]
pub struct UnusedImportBraces;
impl LintPass for UnusedImportBraces {
fn get_lints(&self) -> LintArray {
lint_array!(UNUSED_IMPORT_BRACES)
}
}
impl LateLintPass for UnusedImportBraces {
fn check_item(&mut self, cx: &LateContext, item: &hir::Item) {
if let hir::ItemUse(ref view_path) = item.node {
if let hir::ViewPathList(_, ref items) = view_path.node {
if items.len() == 1 {
if let hir::PathListIdent {ref name, ..} = items[0].node {
let m = format!("braces around {} is unnecessary",
name);
cx.span_lint(UNUSED_IMPORT_BRACES, item.span,
&m[..]);
}
}
}
}
}
}
declare_lint! {
NON_SHORTHAND_FIELD_PATTERNS,
Warn,
@ -1568,33 +922,6 @@ impl LateLintPass for NonShorthandFieldPatterns {
}
}
declare_lint! {
pub UNUSED_UNSAFE,
Warn,
"unnecessary use of an `unsafe` block"
}
#[derive(Copy, Clone)]
pub struct UnusedUnsafe;
impl LintPass for UnusedUnsafe {
fn get_lints(&self) -> LintArray {
lint_array!(UNUSED_UNSAFE)
}
}
impl LateLintPass for UnusedUnsafe {
fn check_expr(&mut self, cx: &LateContext, e: &hir::Expr) {
if let hir::ExprBlock(ref blk) = e.node {
// Don't warn about generated blocks, that'll just pollute the output.
if blk.rules == hir::UnsafeBlock(hir::UserProvided) &&
!cx.tcx.used_unsafe.borrow().contains(&blk.id) {
cx.span_lint(UNUSED_UNSAFE, blk.span, "unnecessary `unsafe` block");
}
}
}
}
declare_lint! {
UNSAFE_CODE,
Allow,
@ -1658,119 +985,6 @@ impl LateLintPass for UnsafeCode {
}
}
declare_lint! {
pub UNUSED_MUT,
Warn,
"detect mut variables which don't need to be mutable"
}
#[derive(Copy, Clone)]
pub struct UnusedMut;
impl UnusedMut {
fn check_unused_mut_pat(&self, cx: &LateContext, pats: &[P<hir::Pat>]) {
// collect all mutable pattern and group their NodeIDs by their Identifier to
// avoid false warnings in match arms with multiple patterns
let mut mutables = FnvHashMap();
for p in pats {
pat_util::pat_bindings(&cx.tcx.def_map, p, |mode, id, _, path1| {
let ident = path1.node;
if let hir::BindByValue(hir::MutMutable) = mode {
if !ident.name.as_str().starts_with("_") {
match mutables.entry(ident.name.usize()) {
Vacant(entry) => { entry.insert(vec![id]); },
Occupied(mut entry) => { entry.get_mut().push(id); },
}
}
}
});
}
let used_mutables = cx.tcx.used_mut_nodes.borrow();
for (_, v) in &mutables {
if !v.iter().any(|e| used_mutables.contains(e)) {
cx.span_lint(UNUSED_MUT, cx.tcx.map.span(v[0]),
"variable does not need to be mutable");
}
}
}
}
impl LintPass for UnusedMut {
fn get_lints(&self) -> LintArray {
lint_array!(UNUSED_MUT)
}
}
impl LateLintPass for UnusedMut {
fn check_expr(&mut self, cx: &LateContext, e: &hir::Expr) {
if let hir::ExprMatch(_, ref arms, _) = e.node {
for a in arms {
self.check_unused_mut_pat(cx, &a.pats)
}
}
}
fn check_stmt(&mut self, cx: &LateContext, s: &hir::Stmt) {
if let hir::StmtDecl(ref d, _) = s.node {
if let hir::DeclLocal(ref l) = d.node {
self.check_unused_mut_pat(cx, slice::ref_slice(&l.pat));
}
}
}
fn check_fn(&mut self, cx: &LateContext,
_: FnKind, decl: &hir::FnDecl,
_: &hir::Block, _: Span, _: ast::NodeId) {
for a in &decl.inputs {
self.check_unused_mut_pat(cx, slice::ref_slice(&a.pat));
}
}
}
declare_lint! {
UNUSED_ALLOCATION,
Warn,
"detects unnecessary allocations that can be eliminated"
}
#[derive(Copy, Clone)]
pub struct UnusedAllocation;
impl LintPass for UnusedAllocation {
fn get_lints(&self) -> LintArray {
lint_array!(UNUSED_ALLOCATION)
}
}
impl LateLintPass for UnusedAllocation {
fn check_expr(&mut self, cx: &LateContext, e: &hir::Expr) {
match e.node {
hir::ExprUnary(hir::UnUniq, _) => (),
_ => return
}
if let Some(adjustment) = cx.tcx.tables.borrow().adjustments.get(&e.id) {
if let adjustment::AdjustDerefRef(adjustment::AutoDerefRef {
ref autoref, ..
}) = *adjustment {
match autoref {
&Some(adjustment::AutoPtr(_, hir::MutImmutable)) => {
cx.span_lint(UNUSED_ALLOCATION, e.span,
"unnecessary allocation, use & instead");
}
&Some(adjustment::AutoPtr(_, hir::MutMutable)) => {
cx.span_lint(UNUSED_ALLOCATION, e.span,
"unnecessary allocation, use &mut instead");
}
_ => ()
}
}
}
}
}
declare_lint! {
MISSING_DOCS,
Allow,

View file

@ -58,7 +58,13 @@ pub use rustc::util as util;
use session::Session;
use lint::LintId;
mod bad_style;
mod builtin;
mod unused;
use bad_style::*;
use builtin::*;
use unused::*;
/// Tell the `LintStore` about all the built-in lints (the ones
/// defined in this crate and the ones defined in
@ -67,7 +73,7 @@ pub fn register_builtins(store: &mut lint::LintStore, sess: Option<&Session>) {
macro_rules! add_builtin {
($sess:ident, $($name:ident),*,) => (
{$(
store.register_late_pass($sess, false, box builtin::$name);
store.register_late_pass($sess, false, box $name);
)*}
)
}
@ -75,7 +81,7 @@ pub fn register_builtins(store: &mut lint::LintStore, sess: Option<&Session>) {
macro_rules! add_early_builtin {
($sess:ident, $($name:ident),*,) => (
{$(
store.register_early_pass($sess, false, box builtin::$name);
store.register_early_pass($sess, false, box $name);
)*}
)
}
@ -83,14 +89,14 @@ pub fn register_builtins(store: &mut lint::LintStore, sess: Option<&Session>) {
macro_rules! add_builtin_with_new {
($sess:ident, $($name:ident),*,) => (
{$(
store.register_late_pass($sess, false, box builtin::$name::new());
store.register_late_pass($sess, false, box $name::new());
)*}
)
}
macro_rules! add_lint_group {
($sess:ident, $name:expr, $($lint:ident),*) => (
store.register_group($sess, false, $name, vec![$(LintId::of(builtin::$lint)),*]);
store.register_group($sess, false, $name, vec![$(LintId::of($lint)),*]);
)
}

468
src/librustc_lint/unused.rs Normal file
View file

@ -0,0 +1,468 @@
// Copyright 2015 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
use metadata::csearch;
use middle::pat_util;
use middle::ty;
use middle::ty::adjustment;
use rustc::front::map as hir_map;
use util::nodemap::FnvHashMap;
use lint::{LateContext, EarlyContext, LintContext, LintArray};
use lint::{LintPass, EarlyLintPass, LateLintPass};
use std::collections::hash_map::Entry::{Occupied, Vacant};
use std::slice;
use syntax::ast;
use syntax::attr::{self, AttrMetaMethods};
use syntax::codemap::Span;
use syntax::feature_gate::{KNOWN_ATTRIBUTES, AttributeType};
use syntax::ptr::P;
use rustc_front::hir;
use rustc_front::visit::FnKind;
declare_lint! {
pub UNUSED_MUT,
Warn,
"detect mut variables which don't need to be mutable"
}
#[derive(Copy, Clone)]
pub struct UnusedMut;
impl UnusedMut {
fn check_unused_mut_pat(&self, cx: &LateContext, pats: &[P<hir::Pat>]) {
// collect all mutable pattern and group their NodeIDs by their Identifier to
// avoid false warnings in match arms with multiple patterns
let mut mutables = FnvHashMap();
for p in pats {
pat_util::pat_bindings(&cx.tcx.def_map, p, |mode, id, _, path1| {
let ident = path1.node;
if let hir::BindByValue(hir::MutMutable) = mode {
if !ident.name.as_str().starts_with("_") {
match mutables.entry(ident.name.usize()) {
Vacant(entry) => { entry.insert(vec![id]); },
Occupied(mut entry) => { entry.get_mut().push(id); },
}
}
}
});
}
let used_mutables = cx.tcx.used_mut_nodes.borrow();
for (_, v) in &mutables {
if !v.iter().any(|e| used_mutables.contains(e)) {
cx.span_lint(UNUSED_MUT, cx.tcx.map.span(v[0]),
"variable does not need to be mutable");
}
}
}
}
impl LintPass for UnusedMut {
fn get_lints(&self) -> LintArray {
lint_array!(UNUSED_MUT)
}
}
impl LateLintPass for UnusedMut {
fn check_expr(&mut self, cx: &LateContext, e: &hir::Expr) {
if let hir::ExprMatch(_, ref arms, _) = e.node {
for a in arms {
self.check_unused_mut_pat(cx, &a.pats)
}
}
}
fn check_stmt(&mut self, cx: &LateContext, s: &hir::Stmt) {
if let hir::StmtDecl(ref d, _) = s.node {
if let hir::DeclLocal(ref l) = d.node {
self.check_unused_mut_pat(cx, slice::ref_slice(&l.pat));
}
}
}
fn check_fn(&mut self, cx: &LateContext,
_: FnKind, decl: &hir::FnDecl,
_: &hir::Block, _: Span, _: ast::NodeId) {
for a in &decl.inputs {
self.check_unused_mut_pat(cx, slice::ref_slice(&a.pat));
}
}
}
declare_lint! {
pub UNUSED_MUST_USE,
Warn,
"unused result of a type flagged as #[must_use]"
}
declare_lint! {
pub UNUSED_RESULTS,
Allow,
"unused result of an expression in a statement"
}
#[derive(Copy, Clone)]
pub struct UnusedResults;
impl LintPass for UnusedResults {
fn get_lints(&self) -> LintArray {
lint_array!(UNUSED_MUST_USE, UNUSED_RESULTS)
}
}
impl LateLintPass for UnusedResults {
fn check_stmt(&mut self, cx: &LateContext, s: &hir::Stmt) {
let expr = match s.node {
hir::StmtSemi(ref expr, _) => &**expr,
_ => return
};
if let hir::ExprRet(..) = expr.node {
return;
}
let t = cx.tcx.expr_ty(&expr);
let warned = match t.sty {
ty::TyTuple(ref tys) if tys.is_empty() => return,
ty::TyBool => return,
ty::TyStruct(def, _) |
ty::TyEnum(def, _) => {
if def.did.is_local() {
if let hir_map::NodeItem(it) = cx.tcx.map.get(def.did.node) {
check_must_use(cx, &it.attrs, s.span)
} else {
false
}
} else {
let attrs = csearch::get_item_attrs(&cx.sess().cstore, def.did);
check_must_use(cx, &attrs[..], s.span)
}
}
_ => false,
};
if !warned {
cx.span_lint(UNUSED_RESULTS, s.span, "unused result");
}
fn check_must_use(cx: &LateContext, attrs: &[ast::Attribute], sp: Span) -> bool {
for attr in attrs {
if attr.check_name("must_use") {
let mut msg = "unused result which must be used".to_string();
// check for #[must_use="..."]
match attr.value_str() {
None => {}
Some(s) => {
msg.push_str(": ");
msg.push_str(&s);
}
}
cx.span_lint(UNUSED_MUST_USE, sp, &msg);
return true;
}
}
false
}
}
}
declare_lint! {
pub UNUSED_UNSAFE,
Warn,
"unnecessary use of an `unsafe` block"
}
#[derive(Copy, Clone)]
pub struct UnusedUnsafe;
impl LintPass for UnusedUnsafe {
fn get_lints(&self) -> LintArray {
lint_array!(UNUSED_UNSAFE)
}
}
impl LateLintPass for UnusedUnsafe {
fn check_expr(&mut self, cx: &LateContext, e: &hir::Expr) {
if let hir::ExprBlock(ref blk) = e.node {
// Don't warn about generated blocks, that'll just pollute the output.
if blk.rules == hir::UnsafeBlock(hir::UserProvided) &&
!cx.tcx.used_unsafe.borrow().contains(&blk.id) {
cx.span_lint(UNUSED_UNSAFE, blk.span, "unnecessary `unsafe` block");
}
}
}
}
declare_lint! {
pub PATH_STATEMENTS,
Warn,
"path statements with no effect"
}
#[derive(Copy, Clone)]
pub struct PathStatements;
impl LintPass for PathStatements {
fn get_lints(&self) -> LintArray {
lint_array!(PATH_STATEMENTS)
}
}
impl LateLintPass for PathStatements {
fn check_stmt(&mut self, cx: &LateContext, s: &hir::Stmt) {
match s.node {
hir::StmtSemi(ref expr, _) => {
match expr.node {
hir::ExprPath(..) => cx.span_lint(PATH_STATEMENTS, s.span,
"path statement with no effect"),
_ => ()
}
}
_ => ()
}
}
}
declare_lint! {
UNUSED_ATTRIBUTES,
Warn,
"detects attributes that were not used by the compiler"
}
#[derive(Copy, Clone)]
pub struct UnusedAttributes;
impl LintPass for UnusedAttributes {
fn get_lints(&self) -> LintArray {
lint_array!(UNUSED_ATTRIBUTES)
}
}
impl LateLintPass for UnusedAttributes {
fn check_attribute(&mut self, cx: &LateContext, attr: &ast::Attribute) {
// Note that check_name() marks the attribute as used if it matches.
for &(ref name, ty, _) in KNOWN_ATTRIBUTES {
match ty {
AttributeType::Whitelisted if attr.check_name(name) => {
break;
},
_ => ()
}
}
let plugin_attributes = cx.sess().plugin_attributes.borrow_mut();
for &(ref name, ty) in plugin_attributes.iter() {
if ty == AttributeType::Whitelisted && attr.check_name(&*name) {
break;
}
}
if !attr::is_used(attr) {
cx.span_lint(UNUSED_ATTRIBUTES, attr.span, "unused attribute");
// Is it a builtin attribute that must be used at the crate level?
let known_crate = KNOWN_ATTRIBUTES.iter().find(|&&(name, ty, _)| {
attr.name() == name &&
ty == AttributeType::CrateLevel
}).is_some();
// Has a plugin registered this attribute as one which must be used at
// the crate level?
let plugin_crate = plugin_attributes.iter()
.find(|&&(ref x, t)| {
&*attr.name() == &*x &&
AttributeType::CrateLevel == t
}).is_some();
if known_crate || plugin_crate {
let msg = match attr.node.style {
ast::AttrOuter => "crate-level attribute should be an inner \
attribute: add an exclamation mark: #![foo]",
ast::AttrInner => "crate-level attribute should be in the \
root module",
};
cx.span_lint(UNUSED_ATTRIBUTES, attr.span, msg);
}
}
}
}
declare_lint! {
UNUSED_PARENS,
Warn,
"`if`, `match`, `while` and `return` do not need parentheses"
}
#[derive(Copy, Clone)]
pub struct UnusedParens;
impl UnusedParens {
fn check_unused_parens_core(&self, cx: &EarlyContext, value: &ast::Expr, msg: &str,
struct_lit_needs_parens: bool) {
if let ast::ExprParen(ref inner) = value.node {
let necessary = struct_lit_needs_parens && contains_exterior_struct_lit(&**inner);
if !necessary {
cx.span_lint(UNUSED_PARENS, value.span,
&format!("unnecessary parentheses around {}", msg))
}
}
/// Expressions that syntactically contain an "exterior" struct
/// literal i.e. not surrounded by any parens or other
/// delimiters, e.g. `X { y: 1 }`, `X { y: 1 }.method()`, `foo
/// == X { y: 1 }` and `X { y: 1 } == foo` all do, but `(X {
/// y: 1 }) == foo` does not.
fn contains_exterior_struct_lit(value: &ast::Expr) -> bool {
match value.node {
ast::ExprStruct(..) => true,
ast::ExprAssign(ref lhs, ref rhs) |
ast::ExprAssignOp(_, ref lhs, ref rhs) |
ast::ExprBinary(_, ref lhs, ref rhs) => {
// X { y: 1 } + X { y: 2 }
contains_exterior_struct_lit(&**lhs) ||
contains_exterior_struct_lit(&**rhs)
}
ast::ExprUnary(_, ref x) |
ast::ExprCast(ref x, _) |
ast::ExprField(ref x, _) |
ast::ExprTupField(ref x, _) |
ast::ExprIndex(ref x, _) => {
// &X { y: 1 }, X { y: 1 }.y
contains_exterior_struct_lit(&**x)
}
ast::ExprMethodCall(_, _, ref exprs) => {
// X { y: 1 }.bar(...)
contains_exterior_struct_lit(&*exprs[0])
}
_ => false
}
}
}
}
impl LintPass for UnusedParens {
fn get_lints(&self) -> LintArray {
lint_array!(UNUSED_PARENS)
}
}
impl EarlyLintPass for UnusedParens {
fn check_expr(&mut self, cx: &EarlyContext, e: &ast::Expr) {
let (value, msg, struct_lit_needs_parens) = match e.node {
ast::ExprIf(ref cond, _, _) => (cond, "`if` condition", true),
ast::ExprWhile(ref cond, _, _) => (cond, "`while` condition", true),
ast::ExprMatch(ref head, _, source) => match source {
ast::MatchSource::Normal => (head, "`match` head expression", true),
ast::MatchSource::IfLetDesugar { .. } => (head, "`if let` head expression", true),
ast::MatchSource::WhileLetDesugar => (head, "`while let` head expression", true),
ast::MatchSource::ForLoopDesugar => (head, "`for` head expression", true),
},
ast::ExprRet(Some(ref value)) => (value, "`return` value", false),
ast::ExprAssign(_, ref value) => (value, "assigned value", false),
ast::ExprAssignOp(_, _, ref value) => (value, "assigned value", false),
_ => return
};
self.check_unused_parens_core(cx, &**value, msg, struct_lit_needs_parens);
}
fn check_stmt(&mut self, cx: &EarlyContext, s: &ast::Stmt) {
let (value, msg) = match s.node {
ast::StmtDecl(ref decl, _) => match decl.node {
ast::DeclLocal(ref local) => match local.init {
Some(ref value) => (value, "assigned value"),
None => return
},
_ => return
},
_ => return
};
self.check_unused_parens_core(cx, &**value, msg, false);
}
}
declare_lint! {
UNUSED_IMPORT_BRACES,
Allow,
"unnecessary braces around an imported item"
}
#[derive(Copy, Clone)]
pub struct UnusedImportBraces;
impl LintPass for UnusedImportBraces {
fn get_lints(&self) -> LintArray {
lint_array!(UNUSED_IMPORT_BRACES)
}
}
impl LateLintPass for UnusedImportBraces {
fn check_item(&mut self, cx: &LateContext, item: &hir::Item) {
if let hir::ItemUse(ref view_path) = item.node {
if let hir::ViewPathList(_, ref items) = view_path.node {
if items.len() == 1 {
if let hir::PathListIdent {ref name, ..} = items[0].node {
let m = format!("braces around {} is unnecessary",
name);
cx.span_lint(UNUSED_IMPORT_BRACES, item.span,
&m[..]);
}
}
}
}
}
}
declare_lint! {
UNUSED_ALLOCATION,
Warn,
"detects unnecessary allocations that can be eliminated"
}
#[derive(Copy, Clone)]
pub struct UnusedAllocation;
impl LintPass for UnusedAllocation {
fn get_lints(&self) -> LintArray {
lint_array!(UNUSED_ALLOCATION)
}
}
impl LateLintPass for UnusedAllocation {
fn check_expr(&mut self, cx: &LateContext, e: &hir::Expr) {
match e.node {
hir::ExprUnary(hir::UnUniq, _) => (),
_ => return
}
if let Some(adjustment) = cx.tcx.tables.borrow().adjustments.get(&e.id) {
if let adjustment::AdjustDerefRef(adjustment::AutoDerefRef {
ref autoref, ..
}) = *adjustment {
match autoref {
&Some(adjustment::AutoPtr(_, hir::MutImmutable)) => {
cx.span_lint(UNUSED_ALLOCATION, e.span,
"unnecessary allocation, use & instead");
}
&Some(adjustment::AutoPtr(_, hir::MutMutable)) => {
cx.span_lint(UNUSED_ALLOCATION, e.span,
"unnecessary allocation, use &mut instead");
}
_ => ()
}
}
}
}
}