2 attr_by_name, attrs::is_proc_macro, is_must_use_ty, is_trait_impl_item, iter_input_pats, match_def_path,
3 must_use_attr, qpath_res, return_ty, snippet, snippet_opt, span_lint, span_lint_and_help, span_lint_and_then,
4 trait_ref_of_method, type_is_unsafe_function,
6 use rustc_ast::ast::Attribute;
7 use rustc_data_structures::fx::FxHashSet;
8 use rustc_errors::Applicability;
10 use rustc_hir::intravisit;
11 use rustc_hir::{def::Res, def_id::DefId};
12 use rustc_lint::{LateContext, LateLintPass, LintContext};
13 use rustc_middle::hir::map::Map;
14 use rustc_middle::lint::in_external_macro;
15 use rustc_middle::ty::{self, Ty};
16 use rustc_session::{declare_tool_lint, impl_lint_pass};
17 use rustc_span::source_map::Span;
18 use rustc_target::spec::abi::Abi;
20 declare_clippy_lint! {
21 /// **What it does:** Checks for functions with too many parameters.
23 /// **Why is this bad?** Functions with lots of parameters are considered bad
24 /// style and reduce readability (“what does the 5th parameter mean?”). Consider
25 /// grouping some parameters into a new type.
27 /// **Known problems:** None.
32 /// fn foo(x: u32, y: u32, name: &str, c: Color, w: f32, h: f32, a: f32, b: f32) {
36 pub TOO_MANY_ARGUMENTS,
38 "functions with too many arguments"
41 declare_clippy_lint! {
42 /// **What it does:** Checks for functions with a large amount of lines.
44 /// **Why is this bad?** Functions with a lot of lines are harder to understand
45 /// due to having to look at a larger amount of code to understand what the
46 /// function is doing. Consider splitting the body of the function into
47 /// multiple functions.
49 /// **Known problems:** None.
53 /// fn im_too_long() {
55 /// // ... 100 more LoC
61 "functions with too many lines"
64 declare_clippy_lint! {
65 /// **What it does:** Checks for public functions that dereference raw pointer
66 /// arguments but are not marked unsafe.
68 /// **Why is this bad?** The function should probably be marked `unsafe`, since
69 /// for an arbitrary raw pointer, there is no way of telling for sure if it is
72 /// **Known problems:**
74 /// * It does not check functions recursively so if the pointer is passed to a
75 /// private non-`unsafe` function which does the dereferencing, the lint won't
77 /// * It only checks for arguments whose type are raw pointers, not raw pointers
78 /// got from an argument in some other way (`fn foo(bar: &[*const u8])` or
79 /// `some_argument.get_raw_ptr()`).
84 /// pub fn foo(x: *const u8) {
85 /// println!("{}", unsafe { *x });
89 /// pub unsafe fn foo(x: *const u8) {
90 /// println!("{}", unsafe { *x });
93 pub NOT_UNSAFE_PTR_ARG_DEREF,
95 "public functions dereferencing raw pointer arguments but not marked `unsafe`"
98 declare_clippy_lint! {
99 /// **What it does:** Checks for a [`#[must_use]`] attribute on
100 /// unit-returning functions and methods.
102 /// [`#[must_use]`]: https://doc.rust-lang.org/reference/attributes/diagnostics.html#the-must_use-attribute
104 /// **Why is this bad?** Unit values are useless. The attribute is likely
105 /// a remnant of a refactoring that removed the return type.
107 /// **Known problems:** None.
116 "`#[must_use]` attribute on a unit-returning function / method"
119 declare_clippy_lint! {
120 /// **What it does:** Checks for a [`#[must_use]`] attribute without
121 /// further information on functions and methods that return a type already
122 /// marked as `#[must_use]`.
124 /// [`#[must_use]`]: https://doc.rust-lang.org/reference/attributes/diagnostics.html#the-must_use-attribute
126 /// **Why is this bad?** The attribute isn't needed. Not using the result
127 /// will already be reported. Alternatively, one can add some text to the
128 /// attribute to improve the lint message.
130 /// **Known problems:** None.
135 /// fn double_must_use() -> Result<(), ()> {
136 /// unimplemented!();
141 "`#[must_use]` attribute on a `#[must_use]`-returning function / method"
144 declare_clippy_lint! {
145 /// **What it does:** Checks for public functions that have no
146 /// [`#[must_use]`] attribute, but return something not already marked
147 /// must-use, have no mutable arg and mutate no statics.
149 /// [`#[must_use]`]: https://doc.rust-lang.org/reference/attributes/diagnostics.html#the-must_use-attribute
151 /// **Why is this bad?** Not bad at all, this lint just shows places where
152 /// you could add the attribute.
154 /// **Known problems:** The lint only checks the arguments for mutable
155 /// types without looking if they are actually changed. On the other hand,
156 /// it also ignores a broad range of potentially interesting side effects,
157 /// because we cannot decide whether the programmer intends the function to
158 /// be called for the side effect or the result. Expect many false
159 /// positives. At least we don't lint if the result type is unit or already
164 /// // this could be annotated with `#[must_use]`.
165 /// fn id<T>(t: T) -> T { t }
167 pub MUST_USE_CANDIDATE,
169 "function or method that could take a `#[must_use]` attribute"
172 #[derive(Copy, Clone)]
173 pub struct Functions {
179 pub fn new(threshold: u64, max_lines: u64) -> Self {
180 Self { threshold, max_lines }
184 impl_lint_pass!(Functions => [
187 NOT_UNSAFE_PTR_ARG_DEREF,
193 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for Functions {
196 cx: &LateContext<'a, 'tcx>,
197 kind: intravisit::FnKind<'tcx>,
198 decl: &'tcx hir::FnDecl<'_>,
199 body: &'tcx hir::Body<'_>,
203 let unsafety = match kind {
204 intravisit::FnKind::ItemFn(_, _, hir::FnHeader { unsafety, .. }, _, _) => unsafety,
205 intravisit::FnKind::Method(_, sig, _, _) => sig.header.unsafety,
206 intravisit::FnKind::Closure(_) => return,
209 // don't warn for implementations, it's not their fault
210 if !is_trait_impl_item(cx, hir_id) {
211 // don't lint extern functions decls, it's not their fault either
213 intravisit::FnKind::Method(
216 header: hir::FnHeader { abi: Abi::Rust, .. },
222 | intravisit::FnKind::ItemFn(_, _, hir::FnHeader { abi: Abi::Rust, .. }, _, _) => {
223 self.check_arg_number(cx, decl, span.with_hi(decl.output.span().hi()))
229 Self::check_raw_ptr(cx, unsafety, decl, body, hir_id);
230 self.check_line_number(cx, span, body);
233 fn check_item(&mut self, cx: &LateContext<'a, 'tcx>, item: &'tcx hir::Item<'_>) {
234 let attr = must_use_attr(&item.attrs);
235 if let hir::ItemKind::Fn(ref sig, ref _generics, ref body_id) = item.kind {
236 if let Some(attr) = attr {
237 let fn_header_span = item.span.with_hi(sig.decl.output.span().hi());
238 check_needless_must_use(cx, &sig.decl, item.hir_id, item.span, fn_header_span, attr);
241 if cx.access_levels.is_exported(item.hir_id)
242 && !is_proc_macro(&item.attrs)
243 && attr_by_name(&item.attrs, "no_mangle").is_none()
245 check_must_use_candidate(
248 cx.tcx.hir().body(*body_id),
251 item.span.with_hi(sig.decl.output.span().hi()),
252 "this function could have a `#[must_use]` attribute",
258 fn check_impl_item(&mut self, cx: &LateContext<'a, 'tcx>, item: &'tcx hir::ImplItem<'_>) {
259 if let hir::ImplItemKind::Fn(ref sig, ref body_id) = item.kind {
260 let attr = must_use_attr(&item.attrs);
261 if let Some(attr) = attr {
262 let fn_header_span = item.span.with_hi(sig.decl.output.span().hi());
263 check_needless_must_use(cx, &sig.decl, item.hir_id, item.span, fn_header_span, attr);
264 } else if cx.access_levels.is_exported(item.hir_id)
265 && !is_proc_macro(&item.attrs)
266 && trait_ref_of_method(cx, item.hir_id).is_none()
268 check_must_use_candidate(
271 cx.tcx.hir().body(*body_id),
274 item.span.with_hi(sig.decl.output.span().hi()),
275 "this method could have a `#[must_use]` attribute",
281 fn check_trait_item(&mut self, cx: &LateContext<'a, 'tcx>, item: &'tcx hir::TraitItem<'_>) {
282 if let hir::TraitItemKind::Fn(ref sig, ref eid) = item.kind {
283 // don't lint extern functions decls, it's not their fault
284 if sig.header.abi == Abi::Rust {
285 self.check_arg_number(cx, &sig.decl, item.span.with_hi(sig.decl.output.span().hi()));
288 let attr = must_use_attr(&item.attrs);
289 if let Some(attr) = attr {
290 let fn_header_span = item.span.with_hi(sig.decl.output.span().hi());
291 check_needless_must_use(cx, &sig.decl, item.hir_id, item.span, fn_header_span, attr);
293 if let hir::TraitFn::Provided(eid) = *eid {
294 let body = cx.tcx.hir().body(eid);
295 Self::check_raw_ptr(cx, sig.header.unsafety, &sig.decl, body, item.hir_id);
297 if attr.is_none() && cx.access_levels.is_exported(item.hir_id) && !is_proc_macro(&item.attrs) {
298 check_must_use_candidate(
304 item.span.with_hi(sig.decl.output.span().hi()),
305 "this method could have a `#[must_use]` attribute",
313 impl<'a, 'tcx> Functions {
314 fn check_arg_number(self, cx: &LateContext<'_, '_>, decl: &hir::FnDecl<'_>, fn_span: Span) {
315 let args = decl.inputs.len() as u64;
316 if args > self.threshold {
321 &format!("this function has too many arguments ({}/{})", args, self.threshold),
326 fn check_line_number(self, cx: &LateContext<'_, '_>, span: Span, body: &'tcx hir::Body<'_>) {
327 if in_external_macro(cx.sess(), span) {
331 let code_snippet = snippet(cx, body.value.span, "..");
332 let mut line_count: u64 = 0;
333 let mut in_comment = false;
334 let mut code_in_line;
336 // Skip the surrounding function decl.
337 let start_brace_idx = code_snippet.find('{').map_or(0, |i| i + 1);
338 let end_brace_idx = code_snippet.rfind('}').unwrap_or_else(|| code_snippet.len());
339 let function_lines = code_snippet[start_brace_idx..end_brace_idx].lines();
341 for mut line in function_lines {
342 code_in_line = false;
344 line = line.trim_start();
349 match line.find("*/") {
351 line = &line[i + 2..];
358 let multi_idx = line.find("/*").unwrap_or_else(|| line.len());
359 let single_idx = line.find("//").unwrap_or_else(|| line.len());
360 code_in_line |= multi_idx > 0 && single_idx > 0;
361 // Implies multi_idx is below line.len()
362 if multi_idx < single_idx {
363 line = &line[multi_idx + 2..];
375 if line_count > self.max_lines {
376 span_lint(cx, TOO_MANY_LINES, span, "This function has a large number of lines.")
381 cx: &LateContext<'a, 'tcx>,
382 unsafety: hir::Unsafety,
383 decl: &'tcx hir::FnDecl<'_>,
384 body: &'tcx hir::Body<'_>,
387 let expr = &body.value;
388 if unsafety == hir::Unsafety::Normal && cx.access_levels.is_exported(hir_id) {
389 let raw_ptrs = iter_input_pats(decl, body)
390 .zip(decl.inputs.iter())
391 .filter_map(|(arg, ty)| raw_ptr_arg(arg, ty))
392 .collect::<FxHashSet<_>>();
394 if !raw_ptrs.is_empty() {
395 let tables = cx.tcx.body_tables(body.id());
396 let mut v = DerefVisitor {
402 intravisit::walk_expr(&mut v, expr);
408 fn check_needless_must_use(
409 cx: &LateContext<'_, '_>,
410 decl: &hir::FnDecl<'_>,
413 fn_header_span: Span,
416 if in_external_macro(cx.sess(), item_span) {
419 if returns_unit(decl) {
424 "this unit-returning function has a `#[must_use]` attribute",
426 diag.span_suggestion(
428 "remove the attribute",
430 Applicability::MachineApplicable,
434 } else if !attr.is_value_str() && is_must_use_ty(cx, return_ty(cx, item_id)) {
439 "this function has an empty `#[must_use]` attribute, but returns a type already marked as `#[must_use]`",
441 "either add some descriptive text or remove the attribute",
446 fn check_must_use_candidate<'a, 'tcx>(
447 cx: &LateContext<'a, 'tcx>,
448 decl: &'tcx hir::FnDecl<'_>,
449 body: &'tcx hir::Body<'_>,
455 if has_mutable_arg(cx, body)
456 || mutates_static(cx, body)
457 || in_external_macro(cx.sess(), item_span)
458 || returns_unit(decl)
459 || !cx.access_levels.is_exported(item_id)
460 || is_must_use_ty(cx, return_ty(cx, item_id))
464 span_lint_and_then(cx, MUST_USE_CANDIDATE, fn_span, msg, |diag| {
465 if let Some(snippet) = snippet_opt(cx, fn_span) {
466 diag.span_suggestion(
469 format!("#[must_use] {}", snippet),
470 Applicability::MachineApplicable,
476 fn returns_unit(decl: &hir::FnDecl<'_>) -> bool {
478 hir::FnRetTy::DefaultReturn(_) => true,
479 hir::FnRetTy::Return(ref ty) => match ty.kind {
480 hir::TyKind::Tup(ref tys) => tys.is_empty(),
481 hir::TyKind::Never => true,
487 fn has_mutable_arg(cx: &LateContext<'_, '_>, body: &hir::Body<'_>) -> bool {
488 let mut tys = FxHashSet::default();
489 body.params.iter().any(|param| is_mutable_pat(cx, ¶m.pat, &mut tys))
492 fn is_mutable_pat(cx: &LateContext<'_, '_>, pat: &hir::Pat<'_>, tys: &mut FxHashSet<DefId>) -> bool {
493 if let hir::PatKind::Wild = pat.kind {
494 return false; // ignore `_` patterns
496 let def_id = pat.hir_id.owner.to_def_id();
497 if cx.tcx.has_typeck_tables(def_id) {
500 &cx.tcx.typeck_tables_of(def_id.expect_local()).pat_ty(pat),
509 static KNOWN_WRAPPER_TYS: &[&[&str]] = &[&["alloc", "rc", "Rc"], &["std", "sync", "Arc"]];
511 fn is_mutable_ty<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, ty: Ty<'tcx>, span: Span, tys: &mut FxHashSet<DefId>) -> bool {
513 // primitive types are never mutable
514 ty::Bool | ty::Char | ty::Int(_) | ty::Uint(_) | ty::Float(_) | ty::Str => false,
515 ty::Adt(ref adt, ref substs) => {
516 tys.insert(adt.did) && !ty.is_freeze(cx.tcx, cx.param_env, span)
517 || KNOWN_WRAPPER_TYS.iter().any(|path| match_def_path(cx, adt.did, path))
518 && substs.types().any(|ty| is_mutable_ty(cx, ty, span, tys))
520 ty::Tuple(ref substs) => substs.types().any(|ty| is_mutable_ty(cx, ty, span, tys)),
521 ty::Array(ty, _) | ty::Slice(ty) => is_mutable_ty(cx, ty, span, tys),
522 ty::RawPtr(ty::TypeAndMut { ty, mutbl }) | ty::Ref(_, ty, mutbl) => {
523 mutbl == hir::Mutability::Mut || is_mutable_ty(cx, ty, span, tys)
525 // calling something constitutes a side effect, so return true on all callables
526 // also never calls need not be used, so return true for them, too
531 fn raw_ptr_arg(arg: &hir::Param<'_>, ty: &hir::Ty<'_>) -> Option<hir::HirId> {
532 if let (&hir::PatKind::Binding(_, id, _, _), &hir::TyKind::Ptr(_)) = (&arg.pat.kind, &ty.kind) {
539 struct DerefVisitor<'a, 'tcx> {
540 cx: &'a LateContext<'a, 'tcx>,
541 ptrs: FxHashSet<hir::HirId>,
542 tables: &'a ty::TypeckTables<'tcx>,
545 impl<'a, 'tcx> intravisit::Visitor<'tcx> for DerefVisitor<'a, 'tcx> {
546 type Map = Map<'tcx>;
548 fn visit_expr(&mut self, expr: &'tcx hir::Expr<'_>) {
550 hir::ExprKind::Call(ref f, args) => {
551 let ty = self.tables.expr_ty(f);
553 if type_is_unsafe_function(self.cx, ty) {
559 hir::ExprKind::MethodCall(_, _, args, _) => {
560 let def_id = self.tables.type_dependent_def_id(expr.hir_id).unwrap();
561 let base_type = self.cx.tcx.type_of(def_id);
563 if type_is_unsafe_function(self.cx, base_type) {
569 hir::ExprKind::Unary(hir::UnOp::UnDeref, ref ptr) => self.check_arg(ptr),
573 intravisit::walk_expr(self, expr);
576 fn nested_visit_map(&mut self) -> intravisit::NestedVisitorMap<Self::Map> {
577 intravisit::NestedVisitorMap::None
581 impl<'a, 'tcx> DerefVisitor<'a, 'tcx> {
582 fn check_arg(&self, ptr: &hir::Expr<'_>) {
583 if let hir::ExprKind::Path(ref qpath) = ptr.kind {
584 if let Res::Local(id) = qpath_res(self.cx, qpath, ptr.hir_id) {
585 if self.ptrs.contains(&id) {
588 NOT_UNSAFE_PTR_ARG_DEREF,
590 "this public function dereferences a raw pointer but is not marked `unsafe`",
598 struct StaticMutVisitor<'a, 'tcx> {
599 cx: &'a LateContext<'a, 'tcx>,
600 mutates_static: bool,
603 impl<'a, 'tcx> intravisit::Visitor<'tcx> for StaticMutVisitor<'a, 'tcx> {
604 type Map = Map<'tcx>;
606 fn visit_expr(&mut self, expr: &'tcx hir::Expr<'_>) {
607 use hir::ExprKind::{AddrOf, Assign, AssignOp, Call, MethodCall};
609 if self.mutates_static {
613 Call(_, args) | MethodCall(_, _, args, _) => {
614 let mut tys = FxHashSet::default();
616 let def_id = arg.hir_id.owner.to_def_id();
617 if self.cx.tcx.has_typeck_tables(def_id)
620 self.cx.tcx.typeck_tables_of(def_id.expect_local()).expr_ty(arg),
624 && is_mutated_static(self.cx, arg)
626 self.mutates_static = true;
632 Assign(ref target, ..) | AssignOp(_, ref target, _) | AddrOf(_, hir::Mutability::Mut, ref target) => {
633 self.mutates_static |= is_mutated_static(self.cx, target)
639 fn nested_visit_map(&mut self) -> intravisit::NestedVisitorMap<Self::Map> {
640 intravisit::NestedVisitorMap::None
644 fn is_mutated_static(cx: &LateContext<'_, '_>, e: &hir::Expr<'_>) -> bool {
645 use hir::ExprKind::{Field, Index, Path};
649 if let Res::Local(_) = qpath_res(cx, qpath, e.hir_id) {
655 Field(ref inner, _) | Index(ref inner, _) => is_mutated_static(cx, inner),
660 fn mutates_static<'a, 'tcx>(cx: &'a LateContext<'a, 'tcx>, body: &'tcx hir::Body<'_>) -> bool {
661 let mut v = StaticMutVisitor {
663 mutates_static: false,
665 intravisit::walk_expr(&mut v, &body.value);