2 attr_by_name, attrs::is_proc_macro, is_must_use_ty, is_trait_impl_item, is_type_diagnostic_item, iter_input_pats,
3 match_def_path, must_use_attr, path_to_local, return_ty, snippet, snippet_opt, span_lint, span_lint_and_help,
4 span_lint_and_then, trait_ref_of_method, type_is_unsafe_function,
6 use if_chain::if_chain;
7 use rustc_ast::ast::Attribute;
8 use rustc_data_structures::fx::FxHashSet;
9 use rustc_errors::Applicability;
11 use rustc_hir::intravisit;
12 use rustc_hir::{def::Res, def_id::DefId, QPath};
13 use rustc_lint::{LateContext, LateLintPass, LintContext};
14 use rustc_middle::hir::map::Map;
15 use rustc_middle::lint::in_external_macro;
16 use rustc_middle::ty::{self, Ty};
17 use rustc_session::{declare_tool_lint, impl_lint_pass};
18 use rustc_span::source_map::Span;
20 use rustc_target::spec::abi::Abi;
21 use rustc_typeck::hir_ty_to_ty;
23 declare_clippy_lint! {
24 /// **What it does:** Checks for functions with too many parameters.
26 /// **Why is this bad?** Functions with lots of parameters are considered bad
27 /// style and reduce readability (“what does the 5th parameter mean?”). Consider
28 /// grouping some parameters into a new type.
30 /// **Known problems:** None.
35 /// fn foo(x: u32, y: u32, name: &str, c: Color, w: f32, h: f32, a: f32, b: f32) {
39 pub TOO_MANY_ARGUMENTS,
41 "functions with too many arguments"
44 declare_clippy_lint! {
45 /// **What it does:** Checks for functions with a large amount of lines.
47 /// **Why is this bad?** Functions with a lot of lines are harder to understand
48 /// due to having to look at a larger amount of code to understand what the
49 /// function is doing. Consider splitting the body of the function into
50 /// multiple functions.
52 /// **Known problems:** None.
56 /// fn im_too_long() {
58 /// // ... 100 more LoC
64 "functions with too many lines"
67 declare_clippy_lint! {
68 /// **What it does:** Checks for public functions that dereference raw pointer
69 /// arguments but are not marked unsafe.
71 /// **Why is this bad?** The function should probably be marked `unsafe`, since
72 /// for an arbitrary raw pointer, there is no way of telling for sure if it is
75 /// **Known problems:**
77 /// * It does not check functions recursively so if the pointer is passed to a
78 /// private non-`unsafe` function which does the dereferencing, the lint won't
80 /// * It only checks for arguments whose type are raw pointers, not raw pointers
81 /// got from an argument in some other way (`fn foo(bar: &[*const u8])` or
82 /// `some_argument.get_raw_ptr()`).
87 /// pub fn foo(x: *const u8) {
88 /// println!("{}", unsafe { *x });
92 /// pub unsafe fn foo(x: *const u8) {
93 /// println!("{}", unsafe { *x });
96 pub NOT_UNSAFE_PTR_ARG_DEREF,
98 "public functions dereferencing raw pointer arguments but not marked `unsafe`"
101 declare_clippy_lint! {
102 /// **What it does:** Checks for a [`#[must_use]`] attribute on
103 /// unit-returning functions and methods.
105 /// [`#[must_use]`]: https://doc.rust-lang.org/reference/attributes/diagnostics.html#the-must_use-attribute
107 /// **Why is this bad?** Unit values are useless. The attribute is likely
108 /// a remnant of a refactoring that removed the return type.
110 /// **Known problems:** None.
119 "`#[must_use]` attribute on a unit-returning function / method"
122 declare_clippy_lint! {
123 /// **What it does:** Checks for a [`#[must_use]`] attribute without
124 /// further information on functions and methods that return a type already
125 /// marked as `#[must_use]`.
127 /// [`#[must_use]`]: https://doc.rust-lang.org/reference/attributes/diagnostics.html#the-must_use-attribute
129 /// **Why is this bad?** The attribute isn't needed. Not using the result
130 /// will already be reported. Alternatively, one can add some text to the
131 /// attribute to improve the lint message.
133 /// **Known problems:** None.
138 /// fn double_must_use() -> Result<(), ()> {
139 /// unimplemented!();
144 "`#[must_use]` attribute on a `#[must_use]`-returning function / method"
147 declare_clippy_lint! {
148 /// **What it does:** Checks for public functions that have no
149 /// [`#[must_use]`] attribute, but return something not already marked
150 /// must-use, have no mutable arg and mutate no statics.
152 /// [`#[must_use]`]: https://doc.rust-lang.org/reference/attributes/diagnostics.html#the-must_use-attribute
154 /// **Why is this bad?** Not bad at all, this lint just shows places where
155 /// you could add the attribute.
157 /// **Known problems:** The lint only checks the arguments for mutable
158 /// types without looking if they are actually changed. On the other hand,
159 /// it also ignores a broad range of potentially interesting side effects,
160 /// because we cannot decide whether the programmer intends the function to
161 /// be called for the side effect or the result. Expect many false
162 /// positives. At least we don't lint if the result type is unit or already
167 /// // this could be annotated with `#[must_use]`.
168 /// fn id<T>(t: T) -> T { t }
170 pub MUST_USE_CANDIDATE,
172 "function or method that could take a `#[must_use]` attribute"
175 declare_clippy_lint! {
176 /// **What it does:** Checks for public functions that return a `Result`
177 /// with an `Err` type of `()`. It suggests using a custom type that
178 /// implements [`std::error::Error`].
180 /// **Why is this bad?** Unit does not implement `Error` and carries no
181 /// further information about what went wrong.
183 /// **Known problems:** Of course, this lint assumes that `Result` is used
184 /// for a fallible operation (which is after all the intended use). However
185 /// code may opt to (mis)use it as a basic two-variant-enum. In that case,
186 /// the suggestion is misguided, and the code should use a custom enum
191 /// pub fn read_u8() -> Result<u8, ()> { Err(()) }
194 /// ```rust,should_panic
198 /// pub struct EndOfStream;
200 /// impl fmt::Display for EndOfStream {
201 /// fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
202 /// write!(f, "End of Stream")
206 /// impl std::error::Error for EndOfStream { }
208 /// pub fn read_u8() -> Result<u8, EndOfStream> { Err(EndOfStream) }
210 ///# read_u8().unwrap();
214 /// Note that there are crates that simplify creating the error type, e.g.
215 /// [`thiserror`](https://docs.rs/thiserror).
218 "public function returning `Result` with an `Err` type of `()`"
221 #[derive(Copy, Clone)]
222 pub struct Functions {
228 pub fn new(threshold: u64, max_lines: u64) -> Self {
229 Self { threshold, max_lines }
233 impl_lint_pass!(Functions => [
236 NOT_UNSAFE_PTR_ARG_DEREF,
243 impl<'tcx> LateLintPass<'tcx> for Functions {
246 cx: &LateContext<'tcx>,
247 kind: intravisit::FnKind<'tcx>,
248 decl: &'tcx hir::FnDecl<'_>,
249 body: &'tcx hir::Body<'_>,
253 let unsafety = match kind {
254 intravisit::FnKind::ItemFn(_, _, hir::FnHeader { unsafety, .. }, _) => unsafety,
255 intravisit::FnKind::Method(_, sig, _) => sig.header.unsafety,
256 intravisit::FnKind::Closure => return,
259 // don't warn for implementations, it's not their fault
260 if !is_trait_impl_item(cx, hir_id) {
261 // don't lint extern functions decls, it's not their fault either
263 intravisit::FnKind::Method(
266 header: hir::FnHeader { abi: Abi::Rust, .. },
271 | intravisit::FnKind::ItemFn(_, _, hir::FnHeader { abi: Abi::Rust, .. }, _) => {
272 self.check_arg_number(cx, decl, span.with_hi(decl.output.span().hi()))
278 Self::check_raw_ptr(cx, unsafety, decl, body, hir_id);
279 self.check_line_number(cx, span, body);
282 fn check_item(&mut self, cx: &LateContext<'tcx>, item: &'tcx hir::Item<'_>) {
283 let attrs = cx.tcx.hir().attrs(item.hir_id());
284 let attr = must_use_attr(attrs);
285 if let hir::ItemKind::Fn(ref sig, ref _generics, ref body_id) = item.kind {
286 let is_public = cx.access_levels.is_exported(item.hir_id());
287 let fn_header_span = item.span.with_hi(sig.decl.output.span().hi());
289 check_result_unit_err(cx, &sig.decl, item.span, fn_header_span);
291 if let Some(attr) = attr {
292 check_needless_must_use(cx, &sig.decl, item.hir_id(), item.span, fn_header_span, attr);
295 if is_public && !is_proc_macro(cx.sess(), attrs) && attr_by_name(attrs, "no_mangle").is_none() {
296 check_must_use_candidate(
299 cx.tcx.hir().body(*body_id),
302 item.span.with_hi(sig.decl.output.span().hi()),
303 "this function could have a `#[must_use]` attribute",
309 fn check_impl_item(&mut self, cx: &LateContext<'tcx>, item: &'tcx hir::ImplItem<'_>) {
310 if let hir::ImplItemKind::Fn(ref sig, ref body_id) = item.kind {
311 let is_public = cx.access_levels.is_exported(item.hir_id());
312 let fn_header_span = item.span.with_hi(sig.decl.output.span().hi());
313 if is_public && trait_ref_of_method(cx, item.hir_id()).is_none() {
314 check_result_unit_err(cx, &sig.decl, item.span, fn_header_span);
316 let attrs = cx.tcx.hir().attrs(item.hir_id());
317 let attr = must_use_attr(attrs);
318 if let Some(attr) = attr {
319 check_needless_must_use(cx, &sig.decl, item.hir_id(), item.span, fn_header_span, attr);
320 } else if is_public && !is_proc_macro(cx.sess(), attrs) && trait_ref_of_method(cx, item.hir_id()).is_none()
322 check_must_use_candidate(
325 cx.tcx.hir().body(*body_id),
328 item.span.with_hi(sig.decl.output.span().hi()),
329 "this method could have a `#[must_use]` attribute",
335 fn check_trait_item(&mut self, cx: &LateContext<'tcx>, item: &'tcx hir::TraitItem<'_>) {
336 if let hir::TraitItemKind::Fn(ref sig, ref eid) = item.kind {
337 // don't lint extern functions decls, it's not their fault
338 if sig.header.abi == Abi::Rust {
339 self.check_arg_number(cx, &sig.decl, item.span.with_hi(sig.decl.output.span().hi()));
341 let is_public = cx.access_levels.is_exported(item.hir_id());
342 let fn_header_span = item.span.with_hi(sig.decl.output.span().hi());
344 check_result_unit_err(cx, &sig.decl, item.span, fn_header_span);
347 let attrs = cx.tcx.hir().attrs(item.hir_id());
348 let attr = must_use_attr(attrs);
349 if let Some(attr) = attr {
350 check_needless_must_use(cx, &sig.decl, item.hir_id(), item.span, fn_header_span, attr);
352 if let hir::TraitFn::Provided(eid) = *eid {
353 let body = cx.tcx.hir().body(eid);
354 Self::check_raw_ptr(cx, sig.header.unsafety, &sig.decl, body, item.hir_id());
356 if attr.is_none() && is_public && !is_proc_macro(cx.sess(), attrs) {
357 check_must_use_candidate(
363 item.span.with_hi(sig.decl.output.span().hi()),
364 "this method could have a `#[must_use]` attribute",
372 impl<'tcx> Functions {
373 fn check_arg_number(self, cx: &LateContext<'_>, decl: &hir::FnDecl<'_>, fn_span: Span) {
374 let args = decl.inputs.len() as u64;
375 if args > self.threshold {
380 &format!("this function has too many arguments ({}/{})", args, self.threshold),
385 fn check_line_number(self, cx: &LateContext<'_>, span: Span, body: &'tcx hir::Body<'_>) {
386 if in_external_macro(cx.sess(), span) {
390 let code_snippet = snippet(cx, body.value.span, "..");
391 let mut line_count: u64 = 0;
392 let mut in_comment = false;
393 let mut code_in_line;
395 // Skip the surrounding function decl.
396 let start_brace_idx = code_snippet.find('{').map_or(0, |i| i + 1);
397 let end_brace_idx = code_snippet.rfind('}').unwrap_or_else(|| code_snippet.len());
398 let function_lines = code_snippet[start_brace_idx..end_brace_idx].lines();
400 for mut line in function_lines {
401 code_in_line = false;
403 line = line.trim_start();
408 if let Some(i) = line.find("*/") {
409 line = &line[i + 2..];
414 let multi_idx = line.find("/*").unwrap_or_else(|| line.len());
415 let single_idx = line.find("//").unwrap_or_else(|| line.len());
416 code_in_line |= multi_idx > 0 && single_idx > 0;
417 // Implies multi_idx is below line.len()
418 if multi_idx < single_idx {
419 line = &line[multi_idx + 2..];
431 if line_count > self.max_lines {
436 &format!("this function has too many lines ({}/{})", line_count, self.max_lines),
442 cx: &LateContext<'tcx>,
443 unsafety: hir::Unsafety,
444 decl: &'tcx hir::FnDecl<'_>,
445 body: &'tcx hir::Body<'_>,
448 let expr = &body.value;
449 if unsafety == hir::Unsafety::Normal && cx.access_levels.is_exported(hir_id) {
450 let raw_ptrs = iter_input_pats(decl, body)
451 .zip(decl.inputs.iter())
452 .filter_map(|(arg, ty)| raw_ptr_arg(arg, ty))
453 .collect::<FxHashSet<_>>();
455 if !raw_ptrs.is_empty() {
456 let typeck_results = cx.tcx.typeck_body(body.id());
457 let mut v = DerefVisitor {
463 intravisit::walk_expr(&mut v, expr);
469 fn check_result_unit_err(cx: &LateContext<'_>, decl: &hir::FnDecl<'_>, item_span: Span, fn_header_span: Span) {
471 if !in_external_macro(cx.sess(), item_span);
472 if let hir::FnRetTy::Return(ref ty) = decl.output;
473 let ty = hir_ty_to_ty(cx.tcx, ty);
474 if is_type_diagnostic_item(cx, ty, sym::result_type);
475 if let ty::Adt(_, substs) = ty.kind();
476 let err_ty = substs.type_at(1);
483 "this returns a `Result<_, ()>",
485 "use a custom Error type instead",
491 fn check_needless_must_use(
492 cx: &LateContext<'_>,
493 decl: &hir::FnDecl<'_>,
496 fn_header_span: Span,
499 if in_external_macro(cx.sess(), item_span) {
502 if returns_unit(decl) {
507 "this unit-returning function has a `#[must_use]` attribute",
509 diag.span_suggestion(
511 "remove the attribute",
513 Applicability::MachineApplicable,
517 } else if !attr.is_value_str() && is_must_use_ty(cx, return_ty(cx, item_id)) {
522 "this function has an empty `#[must_use]` attribute, but returns a type already marked as `#[must_use]`",
524 "either add some descriptive text or remove the attribute",
529 fn check_must_use_candidate<'tcx>(
530 cx: &LateContext<'tcx>,
531 decl: &'tcx hir::FnDecl<'_>,
532 body: &'tcx hir::Body<'_>,
538 if has_mutable_arg(cx, body)
539 || mutates_static(cx, body)
540 || in_external_macro(cx.sess(), item_span)
541 || returns_unit(decl)
542 || !cx.access_levels.is_exported(item_id)
543 || is_must_use_ty(cx, return_ty(cx, item_id))
547 span_lint_and_then(cx, MUST_USE_CANDIDATE, fn_span, msg, |diag| {
548 if let Some(snippet) = snippet_opt(cx, fn_span) {
549 diag.span_suggestion(
552 format!("#[must_use] {}", snippet),
553 Applicability::MachineApplicable,
559 fn returns_unit(decl: &hir::FnDecl<'_>) -> bool {
561 hir::FnRetTy::DefaultReturn(_) => true,
562 hir::FnRetTy::Return(ref ty) => match ty.kind {
563 hir::TyKind::Tup(ref tys) => tys.is_empty(),
564 hir::TyKind::Never => true,
570 fn has_mutable_arg(cx: &LateContext<'_>, body: &hir::Body<'_>) -> bool {
571 let mut tys = FxHashSet::default();
572 body.params.iter().any(|param| is_mutable_pat(cx, ¶m.pat, &mut tys))
575 fn is_mutable_pat(cx: &LateContext<'_>, pat: &hir::Pat<'_>, tys: &mut FxHashSet<DefId>) -> bool {
576 if let hir::PatKind::Wild = pat.kind {
577 return false; // ignore `_` patterns
579 if cx.tcx.has_typeck_results(pat.hir_id.owner.to_def_id()) {
580 is_mutable_ty(cx, &cx.tcx.typeck(pat.hir_id.owner).pat_ty(pat), pat.span, tys)
586 static KNOWN_WRAPPER_TYS: &[&[&str]] = &[&["alloc", "rc", "Rc"], &["std", "sync", "Arc"]];
588 fn is_mutable_ty<'tcx>(cx: &LateContext<'tcx>, ty: Ty<'tcx>, span: Span, tys: &mut FxHashSet<DefId>) -> bool {
590 // primitive types are never mutable
591 ty::Bool | ty::Char | ty::Int(_) | ty::Uint(_) | ty::Float(_) | ty::Str => false,
592 ty::Adt(ref adt, ref substs) => {
593 tys.insert(adt.did) && !ty.is_freeze(cx.tcx.at(span), cx.param_env)
594 || KNOWN_WRAPPER_TYS.iter().any(|path| match_def_path(cx, adt.did, path))
595 && substs.types().any(|ty| is_mutable_ty(cx, ty, span, tys))
597 ty::Tuple(ref substs) => substs.types().any(|ty| is_mutable_ty(cx, ty, span, tys)),
598 ty::Array(ty, _) | ty::Slice(ty) => is_mutable_ty(cx, ty, span, tys),
599 ty::RawPtr(ty::TypeAndMut { ty, mutbl }) | ty::Ref(_, ty, mutbl) => {
600 mutbl == hir::Mutability::Mut || is_mutable_ty(cx, ty, span, tys)
602 // calling something constitutes a side effect, so return true on all callables
603 // also never calls need not be used, so return true for them, too
608 fn raw_ptr_arg(arg: &hir::Param<'_>, ty: &hir::Ty<'_>) -> Option<hir::HirId> {
609 if let (&hir::PatKind::Binding(_, id, _, _), &hir::TyKind::Ptr(_)) = (&arg.pat.kind, &ty.kind) {
616 struct DerefVisitor<'a, 'tcx> {
617 cx: &'a LateContext<'tcx>,
618 ptrs: FxHashSet<hir::HirId>,
619 typeck_results: &'a ty::TypeckResults<'tcx>,
622 impl<'a, 'tcx> intravisit::Visitor<'tcx> for DerefVisitor<'a, 'tcx> {
623 type Map = Map<'tcx>;
625 fn visit_expr(&mut self, expr: &'tcx hir::Expr<'_>) {
627 hir::ExprKind::Call(ref f, args) => {
628 let ty = self.typeck_results.expr_ty(f);
630 if type_is_unsafe_function(self.cx, ty) {
636 hir::ExprKind::MethodCall(_, _, args, _) => {
637 let def_id = self.typeck_results.type_dependent_def_id(expr.hir_id).unwrap();
638 let base_type = self.cx.tcx.type_of(def_id);
640 if type_is_unsafe_function(self.cx, base_type) {
646 hir::ExprKind::Unary(hir::UnOp::Deref, ref ptr) => self.check_arg(ptr),
650 intravisit::walk_expr(self, expr);
653 fn nested_visit_map(&mut self) -> intravisit::NestedVisitorMap<Self::Map> {
654 intravisit::NestedVisitorMap::None
658 impl<'a, 'tcx> DerefVisitor<'a, 'tcx> {
659 fn check_arg(&self, ptr: &hir::Expr<'_>) {
660 if let Some(id) = path_to_local(ptr) {
661 if self.ptrs.contains(&id) {
664 NOT_UNSAFE_PTR_ARG_DEREF,
666 "this public function dereferences a raw pointer but is not marked `unsafe`",
673 struct StaticMutVisitor<'a, 'tcx> {
674 cx: &'a LateContext<'tcx>,
675 mutates_static: bool,
678 impl<'a, 'tcx> intravisit::Visitor<'tcx> for StaticMutVisitor<'a, 'tcx> {
679 type Map = Map<'tcx>;
681 fn visit_expr(&mut self, expr: &'tcx hir::Expr<'_>) {
682 use hir::ExprKind::{AddrOf, Assign, AssignOp, Call, MethodCall};
684 if self.mutates_static {
688 Call(_, args) | MethodCall(_, _, args, _) => {
689 let mut tys = FxHashSet::default();
691 if self.cx.tcx.has_typeck_results(arg.hir_id.owner.to_def_id())
694 self.cx.tcx.typeck(arg.hir_id.owner).expr_ty(arg),
698 && is_mutated_static(arg)
700 self.mutates_static = true;
706 Assign(ref target, ..) | AssignOp(_, ref target, _) | AddrOf(_, hir::Mutability::Mut, ref target) => {
707 self.mutates_static |= is_mutated_static(target)
713 fn nested_visit_map(&mut self) -> intravisit::NestedVisitorMap<Self::Map> {
714 intravisit::NestedVisitorMap::None
718 fn is_mutated_static(e: &hir::Expr<'_>) -> bool {
719 use hir::ExprKind::{Field, Index, Path};
722 Path(QPath::Resolved(_, path)) => !matches!(path.res, Res::Local(_)),
724 Field(ref inner, _) | Index(ref inner, _) => is_mutated_static(inner),
729 fn mutates_static<'tcx>(cx: &LateContext<'tcx>, body: &'tcx hir::Body<'_>) -> bool {
730 let mut v = StaticMutVisitor {
732 mutates_static: false,
734 intravisit::walk_expr(&mut v, &body.value);