Merge branch 'master' into sugg

This commit is contained in:
mcarton 2016-07-03 23:56:06 +02:00
commit 7778f314f2
No known key found for this signature in database
GPG key ID: 5E427C794CBA45E8
11 changed files with 237 additions and 38 deletions

View file

@ -1,9 +1,11 @@
use rustc::lint::*;
use rustc::hir;
use rustc::hir::intravisit;
use rustc::hir;
use rustc::ty;
use rustc::lint::*;
use std::collections::HashSet;
use syntax::ast;
use syntax::codemap::Span;
use utils::span_lint;
use utils::{span_lint, type_is_unsafe_function};
/// **What it does:** Check for functions with too many parameters.
///
@ -15,7 +17,7 @@ use utils::span_lint;
///
/// **Example:**
///
/// ```
/// ```rust
/// fn foo(x: u32, y: u32, name: &str, c: Color, w: f32, h: f32, a: f32, b: f32) { .. }
/// ```
declare_lint! {
@ -24,6 +26,30 @@ declare_lint! {
"functions with too many arguments"
}
/// **What it does:** Check for public functions that dereferences raw pointer arguments but are
/// not marked unsafe.
///
/// **Why is this bad?** The function should probably be marked `unsafe`, since for an arbitrary
/// raw pointer, there is no way of telling for sure if it is valid.
///
/// **Known problems:**
///
/// * It does not check functions recursively so if the pointer is passed to a private non-
/// `unsafe` function which does the dereferencing, the lint won't trigger.
/// * It only checks for arguments whose type are raw pointers, not raw pointers got from an
/// argument in some other way (`fn foo(bar: &[*const u8])` or `some_argument.get_raw_ptr()`).
///
/// **Example:**
///
/// ```rust
/// pub fn foo(x: *const u8) { println!("{}", unsafe { *x }); }
/// ```
declare_lint! {
pub NOT_UNSAFE_PTR_ARG_DEREF,
Warn,
"public functions dereferencing raw pointer arguments but not marked `unsafe`"
}
#[derive(Copy,Clone)]
pub struct Functions {
threshold: u64,
@ -37,29 +63,41 @@ impl Functions {
impl LintPass for Functions {
fn get_lints(&self) -> LintArray {
lint_array!(TOO_MANY_ARGUMENTS)
lint_array!(TOO_MANY_ARGUMENTS, NOT_UNSAFE_PTR_ARG_DEREF)
}
}
impl LateLintPass for Functions {
fn check_fn(&mut self, cx: &LateContext, _: intravisit::FnKind, decl: &hir::FnDecl, _: &hir::Block, span: Span,
nodeid: ast::NodeId) {
fn check_fn(&mut self, cx: &LateContext, kind: intravisit::FnKind, decl: &hir::FnDecl, block: &hir::Block, span: Span, nodeid: ast::NodeId) {
use rustc::hir::map::Node::*;
if let Some(NodeItem(ref item)) = cx.tcx.map.find(cx.tcx.map.get_parent_node(nodeid)) {
match item.node {
hir::ItemImpl(_, _, _, Some(_), _, _) |
hir::ItemDefaultImpl(..) => return,
_ => (),
}
let is_impl = if let Some(NodeItem(ref item)) = cx.tcx.map.find(cx.tcx.map.get_parent_node(nodeid)) {
matches!(item.node, hir::ItemImpl(_, _, _, Some(_), _, _) | hir::ItemDefaultImpl(..))
} else {
false
};
let unsafety = match kind {
hir::intravisit::FnKind::ItemFn(_, _, unsafety, _, _, _, _) => unsafety,
hir::intravisit::FnKind::Method(_, sig, _, _) => sig.unsafety,
hir::intravisit::FnKind::Closure(_) => return,
};
// don't warn for implementations, it's not their fault
if !is_impl {
self.check_arg_number(cx, decl, span);
}
self.check_arg_number(cx, decl, span);
self.check_raw_ptr(cx, unsafety, decl, block, nodeid);
}
fn check_trait_item(&mut self, cx: &LateContext, item: &hir::TraitItem) {
if let hir::MethodTraitItem(ref sig, _) = item.node {
if let hir::MethodTraitItem(ref sig, ref block) = item.node {
self.check_arg_number(cx, &sig.decl, item.span);
if let Some(ref block) = *block {
self.check_raw_ptr(cx, sig.unsafety, &sig.decl, block, item.id);
}
}
}
}
@ -74,4 +112,75 @@ impl Functions {
&format!("this function has too many arguments ({}/{})", args, self.threshold));
}
}
fn check_raw_ptr(&self, cx: &LateContext, unsafety: hir::Unsafety, decl: &hir::FnDecl, block: &hir::Block, nodeid: ast::NodeId) {
if unsafety == hir::Unsafety::Normal && cx.access_levels.is_exported(nodeid) {
let raw_ptrs = decl.inputs.iter().filter_map(|arg| raw_ptr_arg(cx, arg)).collect::<HashSet<_>>();
if !raw_ptrs.is_empty() {
let mut v = DerefVisitor {
cx: cx,
ptrs: raw_ptrs,
};
hir::intravisit::walk_block(&mut v, block);
}
}
}
}
fn raw_ptr_arg(cx: &LateContext, arg: &hir::Arg) -> Option<hir::def_id::DefId> {
if let (&hir::PatKind::Binding(_, _, _), &hir::TyPtr(_)) = (&arg.pat.node, &arg.ty.node) {
cx.tcx.def_map.borrow().get(&arg.pat.id).map(|pr| pr.full_def().def_id())
} else {
None
}
}
struct DerefVisitor<'a, 'tcx: 'a> {
cx: &'a LateContext<'a, 'tcx>,
ptrs: HashSet<hir::def_id::DefId>,
}
impl<'a, 'tcx, 'v> hir::intravisit::Visitor<'v> for DerefVisitor<'a, 'tcx> {
fn visit_expr(&mut self, expr: &'v hir::Expr) {
match expr.node {
hir::ExprCall(ref f, ref args) => {
let ty = self.cx.tcx.expr_ty(f);
if type_is_unsafe_function(ty) {
for arg in args {
self.check_arg(arg);
}
}
}
hir::ExprMethodCall(_, _, ref args) => {
let method_call = ty::MethodCall::expr(expr.id);
let base_type = self.cx.tcx.tables.borrow().method_map[&method_call].ty;
if type_is_unsafe_function(base_type) {
for arg in args {
self.check_arg(arg);
}
}
}
hir::ExprUnary(hir::UnDeref, ref ptr) => self.check_arg(ptr),
_ => (),
}
hir::intravisit::walk_expr(self, expr);
}
}
impl<'a, 'tcx: 'a> DerefVisitor<'a, 'tcx> {
fn check_arg(&self, ptr: &hir::Expr) {
if let Some(def) = self.cx.tcx.def_map.borrow().get(&ptr.id) {
if self.ptrs.contains(&def.full_def().def_id()) {
span_lint(self.cx,
NOT_UNSAFE_PTR_ARG_DEREF,
ptr.span,
"this public function dereferences a raw pointer but is not marked `unsafe`");
}
}
}
}

View file

@ -324,6 +324,7 @@ pub fn register_plugins(reg: &mut rustc_plugin::Registry) {
format::USELESS_FORMAT,
formatting::SUSPICIOUS_ASSIGNMENT_FORMATTING,
formatting::SUSPICIOUS_ELSE_FORMATTING,
functions::NOT_UNSAFE_PTR_ARG_DEREF,
functions::TOO_MANY_ARGUMENTS,
identity_op::IDENTITY_OP,
len_zero::LEN_WITHOUT_IS_EMPTY,

View file

@ -73,7 +73,7 @@ declare_lint! {
/// |`is_` |`&self` or none |
/// |`to_` |`&self` |
///
/// **Why is this bad?** Consistency breeds readability. If you follow the conventions, your users won't be surprised that they e.g. need to supply a mutable reference to a `as_..` function.
/// **Why is this bad?** Consistency breeds readability. If you follow the conventions, your users won't be surprised that they, e.g., need to supply a mutable reference to a `as_..` function.
///
/// **Known problems:** None
///

View file

@ -714,3 +714,12 @@ pub fn same_tys<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, a: ty::Ty<'tcx>, b: ty::Ty
infcx.can_equate(&new_a, &new_b).is_ok()
})
}
/// Return whether the given type is an `unsafe` function.
pub fn type_is_unsafe_function(ty: ty::Ty) -> bool {
match ty.sty {
ty::TyFnDef(_, _, ref f) |
ty::TyFnPtr(ref f) => f.unsafety == Unsafety::Unsafe,
_ => false,
}
}

View file

@ -1,6 +1,8 @@
use rustc::lint::*;
use rustc::ty::TypeVariants;
use rustc::hir::*;
use rustc_const_eval::EvalHint::ExprTypeChecked;
use rustc_const_eval::eval_const_expr_partial;
use syntax::codemap::Span;
use utils::{higher, snippet, span_lint_and_then};
@ -51,26 +53,30 @@ impl LateLintPass for Pass {
fn check_vec_macro(cx: &LateContext, vec: &Expr, span: Span) {
if let Some(vec_args) = higher::vec_macro(cx, vec) {
span_lint_and_then(cx, USELESS_VEC, span, "useless use of `vec!`", |db| {
let snippet = match vec_args {
higher::VecArgs::Repeat(elem, len) => {
let snippet = match vec_args {
higher::VecArgs::Repeat(elem, len) => {
if eval_const_expr_partial(cx.tcx, len, ExprTypeChecked, None).is_ok() {
format!("&[{}; {}]", snippet(cx, elem.span, "elem"), snippet(cx, len.span, "len")).into()
} else {
return;
}
higher::VecArgs::Vec(args) => {
if let Some(last) = args.iter().last() {
let span = Span {
lo: args[0].span.lo,
hi: last.span.hi,
expn_id: args[0].span.expn_id,
};
}
higher::VecArgs::Vec(args) => {
if let Some(last) = args.iter().last() {
let span = Span {
lo: args[0].span.lo,
hi: last.span.hi,
expn_id: args[0].span.expn_id,
};
format!("&[{}]", snippet(cx, span, "..")).into()
} else {
"&[]".into()
}
format!("&[{}]", snippet(cx, span, "..")).into()
} else {
"&[]".into()
}
};
}
};
span_lint_and_then(cx, USELESS_VEC, span, "useless use of `vec!`", |db| {
db.span_suggestion(span, "you can use a slice directly", snippet);
});
}