2 attrs::is_proc_macro, iter_input_pats, match_def_path, qpath_res, return_ty, snippet, snippet_opt,
3 span_help_and_lint, span_lint, span_lint_and_then, trait_ref_of_method, type_is_unsafe_function,
6 use rustc::hir::{self, def::Res, def_id::DefId, intravisit};
7 use rustc::lint::{in_external_macro, LateContext, LateLintPass, LintArray, LintContext, LintPass};
8 use rustc::ty::{self, Ty};
9 use rustc::{declare_tool_lint, impl_lint_pass};
10 use rustc_data_structures::fx::FxHashSet;
11 use rustc_errors::Applicability;
12 use rustc_target::spec::abi::Abi;
13 use syntax::ast::Attribute;
14 use syntax::source_map::Span;
16 declare_clippy_lint! {
17 /// **What it does:** Checks for functions with too many parameters.
19 /// **Why is this bad?** Functions with lots of parameters are considered bad
20 /// style and reduce readability (“what does the 5th parameter mean?”). Consider
21 /// grouping some parameters into a new type.
23 /// **Known problems:** None.
28 /// fn foo(x: u32, y: u32, name: &str, c: Color, w: f32, h: f32, a: f32, b: f32) {
32 pub TOO_MANY_ARGUMENTS,
34 "functions with too many arguments"
37 declare_clippy_lint! {
38 /// **What it does:** Checks for functions with a large amount of lines.
40 /// **Why is this bad?** Functions with a lot of lines are harder to understand
41 /// due to having to look at a larger amount of code to understand what the
42 /// function is doing. Consider splitting the body of the function into
43 /// multiple functions.
45 /// **Known problems:** None.
49 /// fn im_too_long() {
51 /// // ... 100 more LoC
57 "functions with too many lines"
60 declare_clippy_lint! {
61 /// **What it does:** Checks for public functions that dereference raw pointer
62 /// arguments but are not marked unsafe.
64 /// **Why is this bad?** The function should probably be marked `unsafe`, since
65 /// for an arbitrary raw pointer, there is no way of telling for sure if it is
68 /// **Known problems:**
70 /// * It does not check functions recursively so if the pointer is passed to a
71 /// private non-`unsafe` function which does the dereferencing, the lint won't
73 /// * It only checks for arguments whose type are raw pointers, not raw pointers
74 /// got from an argument in some other way (`fn foo(bar: &[*const u8])` or
75 /// `some_argument.get_raw_ptr()`).
79 /// pub fn foo(x: *const u8) {
80 /// println!("{}", unsafe { *x });
83 pub NOT_UNSAFE_PTR_ARG_DEREF,
85 "public functions dereferencing raw pointer arguments but not marked `unsafe`"
88 declare_clippy_lint! {
89 /// **What it does:** Checks for a [`#[must_use]`] attribute on
90 /// unit-returning functions and methods.
92 /// [`#[must_use]`]: https://doc.rust-lang.org/reference/attributes/diagnostics.html#the-must_use-attribute
94 /// **Why is this bad?** Unit values are useless. The attribute is likely
95 /// a remnant of a refactoring that removed the return type.
97 /// **Known problems:** None.
106 "`#[must_use]` attribute on a unit-returning function / method"
109 declare_clippy_lint! {
110 /// **What it does:** Checks for a [`#[must_use]`] attribute without
111 /// further information on functions and methods that return a type already
112 /// marked as `#[must_use]`.
114 /// [`#[must_use]`]: https://doc.rust-lang.org/reference/attributes/diagnostics.html#the-must_use-attribute
116 /// **Why is this bad?** The attribute isn't needed. Not using the result
117 /// will already be reported. Alternatively, one can add some text to the
118 /// attribute to improve the lint message.
120 /// **Known problems:** None.
125 /// fn double_must_use() -> Result<(), ()> {
126 /// unimplemented!();
131 "`#[must_use]` attribute on a `#[must_use]`-returning function / method"
134 declare_clippy_lint! {
135 /// **What it does:** Checks for public functions that have no
136 /// [`#[must_use]`] attribute, but return something not already marked
137 /// must-use, have no mutable arg and mutate no statics.
139 /// [`#[must_use]`]: https://doc.rust-lang.org/reference/attributes/diagnostics.html#the-must_use-attribute
141 /// **Why is this bad?** Not bad at all, this lint just shows places where
142 /// you could add the attribute.
144 /// **Known problems:** The lint only checks the arguments for mutable
145 /// types without looking if they are actually changed. On the other hand,
146 /// it also ignores a broad range of potentially interesting side effects,
147 /// because we cannot decide whether the programmer intends the function to
148 /// be called for the side effect or the result. Expect many false
149 /// positives. At least we don't lint if the result type is unit or already
154 /// // this could be annotated with `#[must_use]`.
155 /// fn id<T>(t: T) -> T { t }
157 pub MUST_USE_CANDIDATE,
159 "function or method that could take a `#[must_use]` attribute"
162 #[derive(Copy, Clone)]
163 pub struct Functions {
169 pub fn new(threshold: u64, max_lines: u64) -> Self {
170 Self { threshold, max_lines }
174 impl_lint_pass!(Functions => [
177 NOT_UNSAFE_PTR_ARG_DEREF,
183 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for Functions {
186 cx: &LateContext<'a, 'tcx>,
187 kind: intravisit::FnKind<'tcx>,
188 decl: &'tcx hir::FnDecl,
189 body: &'tcx hir::Body,
193 let is_impl = if let Some(hir::Node::Item(item)) = cx.tcx.hir().find(cx.tcx.hir().get_parent_node(hir_id)) {
194 matches!(item.kind, hir::ItemKind::Impl(_, _, _, _, Some(_), _, _))
199 let unsafety = match kind {
200 hir::intravisit::FnKind::ItemFn(_, _, hir::FnHeader { unsafety, .. }, _, _) => unsafety,
201 hir::intravisit::FnKind::Method(_, sig, _, _) => sig.header.unsafety,
202 hir::intravisit::FnKind::Closure(_) => return,
205 // don't warn for implementations, it's not their fault
207 // don't lint extern functions decls, it's not their fault either
209 hir::intravisit::FnKind::Method(
212 header: hir::FnHeader { abi: Abi::Rust, .. },
218 | hir::intravisit::FnKind::ItemFn(_, _, hir::FnHeader { abi: Abi::Rust, .. }, _, _) => {
219 self.check_arg_number(cx, decl, span.with_hi(decl.output.span().hi()))
225 Self::check_raw_ptr(cx, unsafety, decl, body, hir_id);
226 self.check_line_number(cx, span, body);
229 fn check_item(&mut self, cx: &LateContext<'a, 'tcx>, item: &'tcx hir::Item) {
230 let attr = must_use_attr(&item.attrs);
231 if let hir::ItemKind::Fn(ref sig, ref _generics, ref body_id) = item.kind {
232 if let Some(attr) = attr {
233 let fn_header_span = item.span.with_hi(sig.decl.output.span().hi());
234 check_needless_must_use(cx, &sig.decl, item.hir_id, item.span, fn_header_span, attr);
237 if cx.access_levels.is_exported(item.hir_id) && !is_proc_macro(&item.attrs) {
238 check_must_use_candidate(
241 cx.tcx.hir().body(*body_id),
244 item.span.with_hi(sig.decl.output.span().hi()),
245 "this function could have a `#[must_use]` attribute",
251 fn check_impl_item(&mut self, cx: &LateContext<'a, 'tcx>, item: &'tcx hir::ImplItem) {
252 if let hir::ImplItemKind::Method(ref sig, ref body_id) = item.kind {
253 let attr = must_use_attr(&item.attrs);
254 if let Some(attr) = attr {
255 let fn_header_span = item.span.with_hi(sig.decl.output.span().hi());
256 check_needless_must_use(cx, &sig.decl, item.hir_id, item.span, fn_header_span, attr);
257 } else if cx.access_levels.is_exported(item.hir_id)
258 && !is_proc_macro(&item.attrs)
259 && trait_ref_of_method(cx, item.hir_id).is_none()
261 check_must_use_candidate(
264 cx.tcx.hir().body(*body_id),
267 item.span.with_hi(sig.decl.output.span().hi()),
268 "this method could have a `#[must_use]` attribute",
274 fn check_trait_item(&mut self, cx: &LateContext<'a, 'tcx>, item: &'tcx hir::TraitItem) {
275 if let hir::TraitItemKind::Method(ref sig, ref eid) = item.kind {
276 // don't lint extern functions decls, it's not their fault
277 if sig.header.abi == Abi::Rust {
278 self.check_arg_number(cx, &sig.decl, item.span.with_hi(sig.decl.output.span().hi()));
281 let attr = must_use_attr(&item.attrs);
282 if let Some(attr) = attr {
283 let fn_header_span = item.span.with_hi(sig.decl.output.span().hi());
284 check_needless_must_use(cx, &sig.decl, item.hir_id, item.span, fn_header_span, attr);
286 if let hir::TraitMethod::Provided(eid) = *eid {
287 let body = cx.tcx.hir().body(eid);
288 Self::check_raw_ptr(cx, sig.header.unsafety, &sig.decl, body, item.hir_id);
290 if attr.is_none() && cx.access_levels.is_exported(item.hir_id) && !is_proc_macro(&item.attrs) {
291 check_must_use_candidate(
297 item.span.with_hi(sig.decl.output.span().hi()),
298 "this method could have a `#[must_use]` attribute",
306 impl<'a, 'tcx> Functions {
307 fn check_arg_number(self, cx: &LateContext<'_, '_>, decl: &hir::FnDecl, fn_span: Span) {
308 let args = decl.inputs.len() as u64;
309 if args > self.threshold {
314 &format!("this function has too many arguments ({}/{})", args, self.threshold),
319 fn check_line_number(self, cx: &LateContext<'_, '_>, span: Span, body: &'tcx hir::Body) {
320 if in_external_macro(cx.sess(), span) {
324 let code_snippet = snippet(cx, body.value.span, "..");
325 let mut line_count: u64 = 0;
326 let mut in_comment = false;
327 let mut code_in_line;
329 // Skip the surrounding function decl.
330 let start_brace_idx = code_snippet.find('{').map_or(0, |i| i + 1);
331 let end_brace_idx = code_snippet.rfind('}').unwrap_or_else(|| code_snippet.len());
332 let function_lines = code_snippet[start_brace_idx..end_brace_idx].lines();
334 for mut line in function_lines {
335 code_in_line = false;
337 line = line.trim_start();
342 match line.find("*/") {
344 line = &line[i + 2..];
351 let multi_idx = line.find("/*").unwrap_or_else(|| line.len());
352 let single_idx = line.find("//").unwrap_or_else(|| line.len());
353 code_in_line |= multi_idx > 0 && single_idx > 0;
354 // Implies multi_idx is below line.len()
355 if multi_idx < single_idx {
356 line = &line[multi_idx + 2..];
368 if line_count > self.max_lines {
369 span_lint(cx, TOO_MANY_LINES, span, "This function has a large number of lines.")
374 cx: &LateContext<'a, 'tcx>,
375 unsafety: hir::Unsafety,
376 decl: &'tcx hir::FnDecl,
377 body: &'tcx hir::Body,
380 let expr = &body.value;
381 if unsafety == hir::Unsafety::Normal && cx.access_levels.is_exported(hir_id) {
382 let raw_ptrs = iter_input_pats(decl, body)
383 .zip(decl.inputs.iter())
384 .filter_map(|(arg, ty)| raw_ptr_arg(arg, ty))
385 .collect::<FxHashSet<_>>();
387 if !raw_ptrs.is_empty() {
388 let tables = cx.tcx.body_tables(body.id());
389 let mut v = DerefVisitor {
395 hir::intravisit::walk_expr(&mut v, expr);
401 fn check_needless_must_use(
402 cx: &LateContext<'_, '_>,
406 fn_header_span: Span,
409 if in_external_macro(cx.sess(), item_span) {
412 if returns_unit(decl) {
417 "this unit-returning function has a `#[must_use]` attribute",
421 "remove the attribute",
423 Applicability::MachineApplicable,
427 } else if !attr.is_value_str() && is_must_use_ty(cx, return_ty(cx, item_id)) {
432 "this function has an empty `#[must_use]` attribute, but returns a type already marked as `#[must_use]`",
433 "either add some descriptive text or remove the attribute",
438 fn check_must_use_candidate<'a, 'tcx>(
439 cx: &LateContext<'a, 'tcx>,
440 decl: &'tcx hir::FnDecl,
441 body: &'tcx hir::Body,
447 if has_mutable_arg(cx, body)
448 || mutates_static(cx, body)
449 || in_external_macro(cx.sess(), item_span)
450 || returns_unit(decl)
451 || is_must_use_ty(cx, return_ty(cx, item_id))
455 span_lint_and_then(cx, MUST_USE_CANDIDATE, fn_span, msg, |db| {
456 if let Some(snippet) = snippet_opt(cx, fn_span) {
460 format!("#[must_use] {}", snippet),
461 Applicability::MachineApplicable,
467 fn must_use_attr(attrs: &[Attribute]) -> Option<&Attribute> {
468 attrs.iter().find(|attr| {
469 attr.ident().map_or(false, |ident| {
470 let ident: &str = &ident.as_str();
476 fn returns_unit(decl: &hir::FnDecl) -> bool {
478 hir::FunctionRetTy::DefaultReturn(_) => true,
479 hir::FunctionRetTy::Return(ref ty) => match ty.kind {
480 hir::TyKind::Tup(ref tys) => tys.is_empty(),
481 hir::TyKind::Never => true,
487 fn is_must_use_ty<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, ty: Ty<'tcx>) -> bool {
490 Adt(ref adt, _) => must_use_attr(&cx.tcx.get_attrs(adt.did)).is_some(),
491 Foreign(ref did) => must_use_attr(&cx.tcx.get_attrs(*did)).is_some(),
492 Slice(ref ty) | Array(ref ty, _) | RawPtr(ty::TypeAndMut { ref ty, .. }) | Ref(_, ref ty, _) => {
493 // for the Array case we don't need to care for the len == 0 case
494 // because we don't want to lint functions returning empty arrays
495 is_must_use_ty(cx, *ty)
497 Tuple(ref substs) => substs.types().any(|ty| is_must_use_ty(cx, ty)),
498 Opaque(ref def_id, _) => {
499 for (predicate, _) in cx.tcx.predicates_of(*def_id).predicates {
500 if let ty::Predicate::Trait(ref poly_trait_predicate) = predicate {
501 if must_use_attr(&cx.tcx.get_attrs(poly_trait_predicate.skip_binder().trait_ref.def_id)).is_some() {
508 Dynamic(binder, _) => {
509 for predicate in binder.skip_binder().iter() {
510 if let ty::ExistentialPredicate::Trait(ref trait_ref) = predicate {
511 if must_use_attr(&cx.tcx.get_attrs(trait_ref.def_id)).is_some() {
522 fn has_mutable_arg(cx: &LateContext<'_, '_>, body: &hir::Body) -> bool {
523 let mut tys = FxHashSet::default();
524 body.params.iter().any(|param| is_mutable_pat(cx, ¶m.pat, &mut tys))
527 fn is_mutable_pat(cx: &LateContext<'_, '_>, pat: &hir::Pat, tys: &mut FxHashSet<DefId>) -> bool {
528 if let hir::PatKind::Wild = pat.kind {
529 return false; // ignore `_` patterns
531 let def_id = pat.hir_id.owner_def_id();
532 if cx.tcx.has_typeck_tables(def_id) {
533 is_mutable_ty(cx, &cx.tcx.typeck_tables_of(def_id).pat_ty(pat), pat.span, tys)
539 static KNOWN_WRAPPER_TYS: &[&[&str]] = &[&["alloc", "rc", "Rc"], &["std", "sync", "Arc"]];
541 fn is_mutable_ty<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, ty: Ty<'tcx>, span: Span, tys: &mut FxHashSet<DefId>) -> bool {
544 // primitive types are never mutable
545 Bool | Char | Int(_) | Uint(_) | Float(_) | Str => false,
546 Adt(ref adt, ref substs) => {
547 tys.insert(adt.did) && !ty.is_freeze(cx.tcx, cx.param_env, span)
548 || KNOWN_WRAPPER_TYS.iter().any(|path| match_def_path(cx, adt.did, path))
549 && substs.types().any(|ty| is_mutable_ty(cx, ty, span, tys))
551 Tuple(ref substs) => substs.types().any(|ty| is_mutable_ty(cx, ty, span, tys)),
552 Array(ty, _) | Slice(ty) => is_mutable_ty(cx, ty, span, tys),
553 RawPtr(ty::TypeAndMut { ty, mutbl }) | Ref(_, ty, mutbl) => {
554 mutbl == hir::Mutability::Mutable || is_mutable_ty(cx, ty, span, tys)
556 // calling something constitutes a side effect, so return true on all callables
557 // also never calls need not be used, so return true for them, too
562 fn raw_ptr_arg(arg: &hir::Param, ty: &hir::Ty) -> Option<hir::HirId> {
563 if let (&hir::PatKind::Binding(_, id, _, _), &hir::TyKind::Ptr(_)) = (&arg.pat.kind, &ty.kind) {
570 struct DerefVisitor<'a, 'tcx> {
571 cx: &'a LateContext<'a, 'tcx>,
572 ptrs: FxHashSet<hir::HirId>,
573 tables: &'a ty::TypeckTables<'tcx>,
576 impl<'a, 'tcx> intravisit::Visitor<'tcx> for DerefVisitor<'a, 'tcx> {
577 fn visit_expr(&mut self, expr: &'tcx hir::Expr) {
579 hir::ExprKind::Call(ref f, ref args) => {
580 let ty = self.tables.expr_ty(f);
582 if type_is_unsafe_function(self.cx, ty) {
588 hir::ExprKind::MethodCall(_, _, ref args) => {
589 let def_id = self.tables.type_dependent_def_id(expr.hir_id).unwrap();
590 let base_type = self.cx.tcx.type_of(def_id);
592 if type_is_unsafe_function(self.cx, base_type) {
598 hir::ExprKind::Unary(hir::UnDeref, ref ptr) => self.check_arg(ptr),
602 intravisit::walk_expr(self, expr);
605 fn nested_visit_map<'this>(&'this mut self) -> intravisit::NestedVisitorMap<'this, 'tcx> {
606 intravisit::NestedVisitorMap::None
610 impl<'a, 'tcx> DerefVisitor<'a, 'tcx> {
611 fn check_arg(&self, ptr: &hir::Expr) {
612 if let hir::ExprKind::Path(ref qpath) = ptr.kind {
613 if let Res::Local(id) = qpath_res(self.cx, qpath, ptr.hir_id) {
614 if self.ptrs.contains(&id) {
617 NOT_UNSAFE_PTR_ARG_DEREF,
619 "this public function dereferences a raw pointer but is not marked `unsafe`",
627 struct StaticMutVisitor<'a, 'tcx> {
628 cx: &'a LateContext<'a, 'tcx>,
629 mutates_static: bool,
632 impl<'a, 'tcx> intravisit::Visitor<'tcx> for StaticMutVisitor<'a, 'tcx> {
633 fn visit_expr(&mut self, expr: &'tcx hir::Expr) {
634 use hir::ExprKind::*;
636 if self.mutates_static {
640 Call(_, ref args) | MethodCall(_, _, ref args) => {
641 let mut tys = FxHashSet::default();
643 let def_id = arg.hir_id.owner_def_id();
644 if self.cx.tcx.has_typeck_tables(def_id)
647 self.cx.tcx.typeck_tables_of(def_id).expr_ty(arg),
651 && is_mutated_static(self.cx, arg)
653 self.mutates_static = true;
659 Assign(ref target, _) | AssignOp(_, ref target, _) | AddrOf(BorrowKind::Ref, hir::Mutability::Mutable, ref target) => {
660 self.mutates_static |= is_mutated_static(self.cx, target)
666 fn nested_visit_map<'this>(&'this mut self) -> intravisit::NestedVisitorMap<'this, 'tcx> {
667 intravisit::NestedVisitorMap::None
671 fn is_mutated_static(cx: &LateContext<'_, '_>, e: &hir::Expr) -> bool {
672 use hir::ExprKind::*;
676 if let Res::Local(_) = qpath_res(cx, qpath, e.hir_id) {
682 Field(ref inner, _) | Index(ref inner, _) => is_mutated_static(cx, inner),
687 fn mutates_static<'a, 'tcx>(cx: &'a LateContext<'a, 'tcx>, body: &'tcx hir::Body) -> bool {
688 let mut v = StaticMutVisitor {
690 mutates_static: false,
692 intravisit::walk_expr(&mut v, &body.value);