]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/functions.rs
Auto merge of #6194 - giraffate:remove_an_extra_blank_line, r=flip1995
[rust.git] / clippy_lints / src / functions.rs
1 use crate::utils::{
2     attr_by_name, attrs::is_proc_macro, is_must_use_ty, is_trait_impl_item, is_type_diagnostic_item, iter_input_pats,
3     last_path_segment, match_def_path, must_use_attr, qpath_res, return_ty, snippet, snippet_opt, span_lint,
4     span_lint_and_help, span_lint_and_then, trait_ref_of_method, type_is_unsafe_function,
5 };
6 use if_chain::if_chain;
7 use rustc_ast::ast::Attribute;
8 use rustc_data_structures::fx::FxHashSet;
9 use rustc_errors::Applicability;
10 use rustc_hir as hir;
11 use rustc_hir::intravisit;
12 use rustc_hir::{def::Res, def_id::DefId};
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;
19 use rustc_target::spec::abi::Abi;
20 use rustc_typeck::hir_ty_to_ty;
21
22 declare_clippy_lint! {
23     /// **What it does:** Checks for functions with too many parameters.
24     ///
25     /// **Why is this bad?** Functions with lots of parameters are considered bad
26     /// style and reduce readability (“what does the 5th parameter mean?”). Consider
27     /// grouping some parameters into a new type.
28     ///
29     /// **Known problems:** None.
30     ///
31     /// **Example:**
32     /// ```rust
33     /// # struct Color;
34     /// fn foo(x: u32, y: u32, name: &str, c: Color, w: f32, h: f32, a: f32, b: f32) {
35     ///     // ..
36     /// }
37     /// ```
38     pub TOO_MANY_ARGUMENTS,
39     complexity,
40     "functions with too many arguments"
41 }
42
43 declare_clippy_lint! {
44     /// **What it does:** Checks for functions with a large amount of lines.
45     ///
46     /// **Why is this bad?** Functions with a lot of lines are harder to understand
47     /// due to having to look at a larger amount of code to understand what the
48     /// function is doing. Consider splitting the body of the function into
49     /// multiple functions.
50     ///
51     /// **Known problems:** None.
52     ///
53     /// **Example:**
54     /// ```rust
55     /// fn im_too_long() {
56     ///     println!("");
57     ///     // ... 100 more LoC
58     ///     println!("");
59     /// }
60     /// ```
61     pub TOO_MANY_LINES,
62     pedantic,
63     "functions with too many lines"
64 }
65
66 declare_clippy_lint! {
67     /// **What it does:** Checks for public functions that dereference raw pointer
68     /// arguments but are not marked unsafe.
69     ///
70     /// **Why is this bad?** The function should probably be marked `unsafe`, since
71     /// for an arbitrary raw pointer, there is no way of telling for sure if it is
72     /// valid.
73     ///
74     /// **Known problems:**
75     ///
76     /// * It does not check functions recursively so if the pointer is passed to a
77     /// private non-`unsafe` function which does the dereferencing, the lint won't
78     /// trigger.
79     /// * It only checks for arguments whose type are raw pointers, not raw pointers
80     /// got from an argument in some other way (`fn foo(bar: &[*const u8])` or
81     /// `some_argument.get_raw_ptr()`).
82     ///
83     /// **Example:**
84     /// ```rust,ignore
85     /// // Bad
86     /// pub fn foo(x: *const u8) {
87     ///     println!("{}", unsafe { *x });
88     /// }
89     ///
90     /// // Good
91     /// pub unsafe fn foo(x: *const u8) {
92     ///     println!("{}", unsafe { *x });
93     /// }
94     /// ```
95     pub NOT_UNSAFE_PTR_ARG_DEREF,
96     correctness,
97     "public functions dereferencing raw pointer arguments but not marked `unsafe`"
98 }
99
100 declare_clippy_lint! {
101     /// **What it does:** Checks for a [`#[must_use]`] attribute on
102     /// unit-returning functions and methods.
103     ///
104     /// [`#[must_use]`]: https://doc.rust-lang.org/reference/attributes/diagnostics.html#the-must_use-attribute
105     ///
106     /// **Why is this bad?** Unit values are useless. The attribute is likely
107     /// a remnant of a refactoring that removed the return type.
108     ///
109     /// **Known problems:** None.
110     ///
111     /// **Examples:**
112     /// ```rust
113     /// #[must_use]
114     /// fn useless() { }
115     /// ```
116     pub MUST_USE_UNIT,
117     style,
118     "`#[must_use]` attribute on a unit-returning function / method"
119 }
120
121 declare_clippy_lint! {
122     /// **What it does:** Checks for a [`#[must_use]`] attribute without
123     /// further information on functions and methods that return a type already
124     /// marked as `#[must_use]`.
125     ///
126     /// [`#[must_use]`]: https://doc.rust-lang.org/reference/attributes/diagnostics.html#the-must_use-attribute
127     ///
128     /// **Why is this bad?** The attribute isn't needed. Not using the result
129     /// will already be reported. Alternatively, one can add some text to the
130     /// attribute to improve the lint message.
131     ///
132     /// **Known problems:** None.
133     ///
134     /// **Examples:**
135     /// ```rust
136     /// #[must_use]
137     /// fn double_must_use() -> Result<(), ()> {
138     ///     unimplemented!();
139     /// }
140     /// ```
141     pub DOUBLE_MUST_USE,
142     style,
143     "`#[must_use]` attribute on a `#[must_use]`-returning function / method"
144 }
145
146 declare_clippy_lint! {
147     /// **What it does:** Checks for public functions that have no
148     /// [`#[must_use]`] attribute, but return something not already marked
149     /// must-use, have no mutable arg and mutate no statics.
150     ///
151     /// [`#[must_use]`]: https://doc.rust-lang.org/reference/attributes/diagnostics.html#the-must_use-attribute
152     ///
153     /// **Why is this bad?** Not bad at all, this lint just shows places where
154     /// you could add the attribute.
155     ///
156     /// **Known problems:** The lint only checks the arguments for mutable
157     /// types without looking if they are actually changed. On the other hand,
158     /// it also ignores a broad range of potentially interesting side effects,
159     /// because we cannot decide whether the programmer intends the function to
160     /// be called for the side effect or the result. Expect many false
161     /// positives. At least we don't lint if the result type is unit or already
162     /// `#[must_use]`.
163     ///
164     /// **Examples:**
165     /// ```rust
166     /// // this could be annotated with `#[must_use]`.
167     /// fn id<T>(t: T) -> T { t }
168     /// ```
169     pub MUST_USE_CANDIDATE,
170     pedantic,
171     "function or method that could take a `#[must_use]` attribute"
172 }
173
174 declare_clippy_lint! {
175     /// **What it does:** Checks for public functions that return a `Result`
176     /// with an `Err` type of `()`. It suggests using a custom type that
177     /// implements [`std::error::Error`].
178     ///
179     /// **Why is this bad?** Unit does not implement `Error` and carries no
180     /// further information about what went wrong.
181     ///
182     /// **Known problems:** Of course, this lint assumes that `Result` is used
183     /// for a fallible operation (which is after all the intended use). However
184     /// code may opt to (mis)use it as a basic two-variant-enum. In that case,
185     /// the suggestion is misguided, and the code should use a custom enum
186     /// instead.
187     ///
188     /// **Examples:**
189     /// ```rust
190     /// pub fn read_u8() -> Result<u8, ()> { Err(()) }
191     /// ```
192     /// should become
193     /// ```rust,should_panic
194     /// use std::fmt;
195     ///
196     /// #[derive(Debug)]
197     /// pub struct EndOfStream;
198     ///
199     /// impl fmt::Display for EndOfStream {
200     ///     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
201     ///         write!(f, "End of Stream")
202     ///     }
203     /// }
204     ///
205     /// impl std::error::Error for EndOfStream { }
206     ///
207     /// pub fn read_u8() -> Result<u8, EndOfStream> { Err(EndOfStream) }
208     ///# fn main() {
209     ///#     read_u8().unwrap();
210     ///# }
211     /// ```
212     ///
213     /// Note that there are crates that simplify creating the error type, e.g.
214     /// [`thiserror`](https://docs.rs/thiserror).
215     pub RESULT_UNIT_ERR,
216     style,
217     "public function returning `Result` with an `Err` type of `()`"
218 }
219
220 #[derive(Copy, Clone)]
221 pub struct Functions {
222     threshold: u64,
223     max_lines: u64,
224 }
225
226 impl Functions {
227     pub fn new(threshold: u64, max_lines: u64) -> Self {
228         Self { threshold, max_lines }
229     }
230 }
231
232 impl_lint_pass!(Functions => [
233     TOO_MANY_ARGUMENTS,
234     TOO_MANY_LINES,
235     NOT_UNSAFE_PTR_ARG_DEREF,
236     MUST_USE_UNIT,
237     DOUBLE_MUST_USE,
238     MUST_USE_CANDIDATE,
239     RESULT_UNIT_ERR,
240 ]);
241
242 impl<'tcx> LateLintPass<'tcx> for Functions {
243     fn check_fn(
244         &mut self,
245         cx: &LateContext<'tcx>,
246         kind: intravisit::FnKind<'tcx>,
247         decl: &'tcx hir::FnDecl<'_>,
248         body: &'tcx hir::Body<'_>,
249         span: Span,
250         hir_id: hir::HirId,
251     ) {
252         let unsafety = match kind {
253             intravisit::FnKind::ItemFn(_, _, hir::FnHeader { unsafety, .. }, _, _) => unsafety,
254             intravisit::FnKind::Method(_, sig, _, _) => sig.header.unsafety,
255             intravisit::FnKind::Closure(_) => return,
256         };
257
258         // don't warn for implementations, it's not their fault
259         if !is_trait_impl_item(cx, hir_id) {
260             // don't lint extern functions decls, it's not their fault either
261             match kind {
262                 intravisit::FnKind::Method(
263                     _,
264                     &hir::FnSig {
265                         header: hir::FnHeader { abi: Abi::Rust, .. },
266                         ..
267                     },
268                     _,
269                     _,
270                 )
271                 | intravisit::FnKind::ItemFn(_, _, hir::FnHeader { abi: Abi::Rust, .. }, _, _) => {
272                     self.check_arg_number(cx, decl, span.with_hi(decl.output.span().hi()))
273                 },
274                 _ => {},
275             }
276         }
277
278         Self::check_raw_ptr(cx, unsafety, decl, body, hir_id);
279         self.check_line_number(cx, span, body);
280     }
281
282     fn check_item(&mut self, cx: &LateContext<'tcx>, item: &'tcx hir::Item<'_>) {
283         let attr = must_use_attr(&item.attrs);
284         if let hir::ItemKind::Fn(ref sig, ref _generics, ref body_id) = item.kind {
285             let is_public = cx.access_levels.is_exported(item.hir_id);
286             let fn_header_span = item.span.with_hi(sig.decl.output.span().hi());
287             if is_public {
288                 check_result_unit_err(cx, &sig.decl, item.span, fn_header_span);
289             }
290             if let Some(attr) = attr {
291                 check_needless_must_use(cx, &sig.decl, item.hir_id, item.span, fn_header_span, attr);
292                 return;
293             }
294             if is_public && !is_proc_macro(cx.sess(), &item.attrs) && attr_by_name(&item.attrs, "no_mangle").is_none() {
295                 check_must_use_candidate(
296                     cx,
297                     &sig.decl,
298                     cx.tcx.hir().body(*body_id),
299                     item.span,
300                     item.hir_id,
301                     item.span.with_hi(sig.decl.output.span().hi()),
302                     "this function could have a `#[must_use]` attribute",
303                 );
304             }
305         }
306     }
307
308     fn check_impl_item(&mut self, cx: &LateContext<'tcx>, item: &'tcx hir::ImplItem<'_>) {
309         if let hir::ImplItemKind::Fn(ref sig, ref body_id) = item.kind {
310             let is_public = cx.access_levels.is_exported(item.hir_id);
311             let fn_header_span = item.span.with_hi(sig.decl.output.span().hi());
312             if is_public && trait_ref_of_method(cx, item.hir_id).is_none() {
313                 check_result_unit_err(cx, &sig.decl, item.span, fn_header_span);
314             }
315             let attr = must_use_attr(&item.attrs);
316             if let Some(attr) = attr {
317                 check_needless_must_use(cx, &sig.decl, item.hir_id, item.span, fn_header_span, attr);
318             } else if is_public
319                 && !is_proc_macro(cx.sess(), &item.attrs)
320                 && trait_ref_of_method(cx, item.hir_id).is_none()
321             {
322                 check_must_use_candidate(
323                     cx,
324                     &sig.decl,
325                     cx.tcx.hir().body(*body_id),
326                     item.span,
327                     item.hir_id,
328                     item.span.with_hi(sig.decl.output.span().hi()),
329                     "this method could have a `#[must_use]` attribute",
330                 );
331             }
332         }
333     }
334
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()));
340             }
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());
343             if is_public {
344                 check_result_unit_err(cx, &sig.decl, item.span, fn_header_span);
345             }
346
347             let attr = must_use_attr(&item.attrs);
348             if let Some(attr) = attr {
349                 check_needless_must_use(cx, &sig.decl, item.hir_id, item.span, fn_header_span, attr);
350             }
351             if let hir::TraitFn::Provided(eid) = *eid {
352                 let body = cx.tcx.hir().body(eid);
353                 Self::check_raw_ptr(cx, sig.header.unsafety, &sig.decl, body, item.hir_id);
354
355                 if attr.is_none() && is_public && !is_proc_macro(cx.sess(), &item.attrs) {
356                     check_must_use_candidate(
357                         cx,
358                         &sig.decl,
359                         body,
360                         item.span,
361                         item.hir_id,
362                         item.span.with_hi(sig.decl.output.span().hi()),
363                         "this method could have a `#[must_use]` attribute",
364                     );
365                 }
366             }
367         }
368     }
369 }
370
371 impl<'tcx> Functions {
372     fn check_arg_number(self, cx: &LateContext<'_>, decl: &hir::FnDecl<'_>, fn_span: Span) {
373         let args = decl.inputs.len() as u64;
374         if args > self.threshold {
375             span_lint(
376                 cx,
377                 TOO_MANY_ARGUMENTS,
378                 fn_span,
379                 &format!("this function has too many arguments ({}/{})", args, self.threshold),
380             );
381         }
382     }
383
384     fn check_line_number(self, cx: &LateContext<'_>, span: Span, body: &'tcx hir::Body<'_>) {
385         if in_external_macro(cx.sess(), span) {
386             return;
387         }
388
389         let code_snippet = snippet(cx, body.value.span, "..");
390         let mut line_count: u64 = 0;
391         let mut in_comment = false;
392         let mut code_in_line;
393
394         // Skip the surrounding function decl.
395         let start_brace_idx = code_snippet.find('{').map_or(0, |i| i + 1);
396         let end_brace_idx = code_snippet.rfind('}').unwrap_or_else(|| code_snippet.len());
397         let function_lines = code_snippet[start_brace_idx..end_brace_idx].lines();
398
399         for mut line in function_lines {
400             code_in_line = false;
401             loop {
402                 line = line.trim_start();
403                 if line.is_empty() {
404                     break;
405                 }
406                 if in_comment {
407                     match line.find("*/") {
408                         Some(i) => {
409                             line = &line[i + 2..];
410                             in_comment = false;
411                             continue;
412                         },
413                         None => break,
414                     }
415                 } else {
416                     let multi_idx = line.find("/*").unwrap_or_else(|| line.len());
417                     let single_idx = line.find("//").unwrap_or_else(|| line.len());
418                     code_in_line |= multi_idx > 0 && single_idx > 0;
419                     // Implies multi_idx is below line.len()
420                     if multi_idx < single_idx {
421                         line = &line[multi_idx + 2..];
422                         in_comment = true;
423                         continue;
424                     }
425                     break;
426                 }
427             }
428             if code_in_line {
429                 line_count += 1;
430             }
431         }
432
433         if line_count > self.max_lines {
434             span_lint(
435                 cx,
436                 TOO_MANY_LINES,
437                 span,
438                 &format!("this function has too many lines ({}/{})", line_count, self.max_lines),
439             )
440         }
441     }
442
443     fn check_raw_ptr(
444         cx: &LateContext<'tcx>,
445         unsafety: hir::Unsafety,
446         decl: &'tcx hir::FnDecl<'_>,
447         body: &'tcx hir::Body<'_>,
448         hir_id: hir::HirId,
449     ) {
450         let expr = &body.value;
451         if unsafety == hir::Unsafety::Normal && cx.access_levels.is_exported(hir_id) {
452             let raw_ptrs = iter_input_pats(decl, body)
453                 .zip(decl.inputs.iter())
454                 .filter_map(|(arg, ty)| raw_ptr_arg(arg, ty))
455                 .collect::<FxHashSet<_>>();
456
457             if !raw_ptrs.is_empty() {
458                 let typeck_results = cx.tcx.typeck_body(body.id());
459                 let mut v = DerefVisitor {
460                     cx,
461                     ptrs: raw_ptrs,
462                     typeck_results,
463                 };
464
465                 intravisit::walk_expr(&mut v, expr);
466             }
467         }
468     }
469 }
470
471 fn check_result_unit_err(cx: &LateContext<'_>, decl: &hir::FnDecl<'_>, item_span: Span, fn_header_span: Span) {
472     if_chain! {
473         if !in_external_macro(cx.sess(), item_span);
474         if let hir::FnRetTy::Return(ref ty) = decl.output;
475         if let hir::TyKind::Path(ref qpath) = ty.kind;
476         if is_type_diagnostic_item(cx, hir_ty_to_ty(cx.tcx, ty), sym!(result_type));
477         if let Some(ref args) = last_path_segment(qpath).args;
478         if let [_, hir::GenericArg::Type(ref err_ty)] = args.args;
479         if let hir::TyKind::Tup(t) = err_ty.kind;
480         if t.is_empty();
481         then {
482             span_lint_and_help(
483                 cx,
484                 RESULT_UNIT_ERR,
485                 fn_header_span,
486                 "this returns a `Result<_, ()>",
487                 None,
488                 "use a custom Error type instead",
489             );
490         }
491     }
492 }
493
494 fn check_needless_must_use(
495     cx: &LateContext<'_>,
496     decl: &hir::FnDecl<'_>,
497     item_id: hir::HirId,
498     item_span: Span,
499     fn_header_span: Span,
500     attr: &Attribute,
501 ) {
502     if in_external_macro(cx.sess(), item_span) {
503         return;
504     }
505     if returns_unit(decl) {
506         span_lint_and_then(
507             cx,
508             MUST_USE_UNIT,
509             fn_header_span,
510             "this unit-returning function has a `#[must_use]` attribute",
511             |diag| {
512                 diag.span_suggestion(
513                     attr.span,
514                     "remove the attribute",
515                     "".into(),
516                     Applicability::MachineApplicable,
517                 );
518             },
519         );
520     } else if !attr.is_value_str() && is_must_use_ty(cx, return_ty(cx, item_id)) {
521         span_lint_and_help(
522             cx,
523             DOUBLE_MUST_USE,
524             fn_header_span,
525             "this function has an empty `#[must_use]` attribute, but returns a type already marked as `#[must_use]`",
526             None,
527             "either add some descriptive text or remove the attribute",
528         );
529     }
530 }
531
532 fn check_must_use_candidate<'tcx>(
533     cx: &LateContext<'tcx>,
534     decl: &'tcx hir::FnDecl<'_>,
535     body: &'tcx hir::Body<'_>,
536     item_span: Span,
537     item_id: hir::HirId,
538     fn_span: Span,
539     msg: &str,
540 ) {
541     if has_mutable_arg(cx, body)
542         || mutates_static(cx, body)
543         || in_external_macro(cx.sess(), item_span)
544         || returns_unit(decl)
545         || !cx.access_levels.is_exported(item_id)
546         || is_must_use_ty(cx, return_ty(cx, item_id))
547     {
548         return;
549     }
550     span_lint_and_then(cx, MUST_USE_CANDIDATE, fn_span, msg, |diag| {
551         if let Some(snippet) = snippet_opt(cx, fn_span) {
552             diag.span_suggestion(
553                 fn_span,
554                 "add the attribute",
555                 format!("#[must_use] {}", snippet),
556                 Applicability::MachineApplicable,
557             );
558         }
559     });
560 }
561
562 fn returns_unit(decl: &hir::FnDecl<'_>) -> bool {
563     match decl.output {
564         hir::FnRetTy::DefaultReturn(_) => true,
565         hir::FnRetTy::Return(ref ty) => match ty.kind {
566             hir::TyKind::Tup(ref tys) => tys.is_empty(),
567             hir::TyKind::Never => true,
568             _ => false,
569         },
570     }
571 }
572
573 fn has_mutable_arg(cx: &LateContext<'_>, body: &hir::Body<'_>) -> bool {
574     let mut tys = FxHashSet::default();
575     body.params.iter().any(|param| is_mutable_pat(cx, &param.pat, &mut tys))
576 }
577
578 fn is_mutable_pat(cx: &LateContext<'_>, pat: &hir::Pat<'_>, tys: &mut FxHashSet<DefId>) -> bool {
579     if let hir::PatKind::Wild = pat.kind {
580         return false; // ignore `_` patterns
581     }
582     if cx.tcx.has_typeck_results(pat.hir_id.owner.to_def_id()) {
583         is_mutable_ty(cx, &cx.tcx.typeck(pat.hir_id.owner).pat_ty(pat), pat.span, tys)
584     } else {
585         false
586     }
587 }
588
589 static KNOWN_WRAPPER_TYS: &[&[&str]] = &[&["alloc", "rc", "Rc"], &["std", "sync", "Arc"]];
590
591 fn is_mutable_ty<'tcx>(cx: &LateContext<'tcx>, ty: Ty<'tcx>, span: Span, tys: &mut FxHashSet<DefId>) -> bool {
592     match *ty.kind() {
593         // primitive types are never mutable
594         ty::Bool | ty::Char | ty::Int(_) | ty::Uint(_) | ty::Float(_) | ty::Str => false,
595         ty::Adt(ref adt, ref substs) => {
596             tys.insert(adt.did) && !ty.is_freeze(cx.tcx.at(span), cx.param_env)
597                 || KNOWN_WRAPPER_TYS.iter().any(|path| match_def_path(cx, adt.did, path))
598                     && substs.types().any(|ty| is_mutable_ty(cx, ty, span, tys))
599         },
600         ty::Tuple(ref substs) => substs.types().any(|ty| is_mutable_ty(cx, ty, span, tys)),
601         ty::Array(ty, _) | ty::Slice(ty) => is_mutable_ty(cx, ty, span, tys),
602         ty::RawPtr(ty::TypeAndMut { ty, mutbl }) | ty::Ref(_, ty, mutbl) => {
603             mutbl == hir::Mutability::Mut || is_mutable_ty(cx, ty, span, tys)
604         },
605         // calling something constitutes a side effect, so return true on all callables
606         // also never calls need not be used, so return true for them, too
607         _ => true,
608     }
609 }
610
611 fn raw_ptr_arg(arg: &hir::Param<'_>, ty: &hir::Ty<'_>) -> Option<hir::HirId> {
612     if let (&hir::PatKind::Binding(_, id, _, _), &hir::TyKind::Ptr(_)) = (&arg.pat.kind, &ty.kind) {
613         Some(id)
614     } else {
615         None
616     }
617 }
618
619 struct DerefVisitor<'a, 'tcx> {
620     cx: &'a LateContext<'tcx>,
621     ptrs: FxHashSet<hir::HirId>,
622     typeck_results: &'a ty::TypeckResults<'tcx>,
623 }
624
625 impl<'a, 'tcx> intravisit::Visitor<'tcx> for DerefVisitor<'a, 'tcx> {
626     type Map = Map<'tcx>;
627
628     fn visit_expr(&mut self, expr: &'tcx hir::Expr<'_>) {
629         match expr.kind {
630             hir::ExprKind::Call(ref f, args) => {
631                 let ty = self.typeck_results.expr_ty(f);
632
633                 if type_is_unsafe_function(self.cx, ty) {
634                     for arg in args {
635                         self.check_arg(arg);
636                     }
637                 }
638             },
639             hir::ExprKind::MethodCall(_, _, args, _) => {
640                 let def_id = self.typeck_results.type_dependent_def_id(expr.hir_id).unwrap();
641                 let base_type = self.cx.tcx.type_of(def_id);
642
643                 if type_is_unsafe_function(self.cx, base_type) {
644                     for arg in args {
645                         self.check_arg(arg);
646                     }
647                 }
648             },
649             hir::ExprKind::Unary(hir::UnOp::UnDeref, ref ptr) => self.check_arg(ptr),
650             _ => (),
651         }
652
653         intravisit::walk_expr(self, expr);
654     }
655
656     fn nested_visit_map(&mut self) -> intravisit::NestedVisitorMap<Self::Map> {
657         intravisit::NestedVisitorMap::None
658     }
659 }
660
661 impl<'a, 'tcx> DerefVisitor<'a, 'tcx> {
662     fn check_arg(&self, ptr: &hir::Expr<'_>) {
663         if let hir::ExprKind::Path(ref qpath) = ptr.kind {
664             if let Res::Local(id) = qpath_res(self.cx, qpath, ptr.hir_id) {
665                 if self.ptrs.contains(&id) {
666                     span_lint(
667                         self.cx,
668                         NOT_UNSAFE_PTR_ARG_DEREF,
669                         ptr.span,
670                         "this public function dereferences a raw pointer but is not marked `unsafe`",
671                     );
672                 }
673             }
674         }
675     }
676 }
677
678 struct StaticMutVisitor<'a, 'tcx> {
679     cx: &'a LateContext<'tcx>,
680     mutates_static: bool,
681 }
682
683 impl<'a, 'tcx> intravisit::Visitor<'tcx> for StaticMutVisitor<'a, 'tcx> {
684     type Map = Map<'tcx>;
685
686     fn visit_expr(&mut self, expr: &'tcx hir::Expr<'_>) {
687         use hir::ExprKind::{AddrOf, Assign, AssignOp, Call, MethodCall};
688
689         if self.mutates_static {
690             return;
691         }
692         match expr.kind {
693             Call(_, args) | MethodCall(_, _, args, _) => {
694                 let mut tys = FxHashSet::default();
695                 for arg in args {
696                     if self.cx.tcx.has_typeck_results(arg.hir_id.owner.to_def_id())
697                         && is_mutable_ty(
698                             self.cx,
699                             self.cx.tcx.typeck(arg.hir_id.owner).expr_ty(arg),
700                             arg.span,
701                             &mut tys,
702                         )
703                         && is_mutated_static(self.cx, arg)
704                     {
705                         self.mutates_static = true;
706                         return;
707                     }
708                     tys.clear();
709                 }
710             },
711             Assign(ref target, ..) | AssignOp(_, ref target, _) | AddrOf(_, hir::Mutability::Mut, ref target) => {
712                 self.mutates_static |= is_mutated_static(self.cx, target)
713             },
714             _ => {},
715         }
716     }
717
718     fn nested_visit_map(&mut self) -> intravisit::NestedVisitorMap<Self::Map> {
719         intravisit::NestedVisitorMap::None
720     }
721 }
722
723 fn is_mutated_static(cx: &LateContext<'_>, e: &hir::Expr<'_>) -> bool {
724     use hir::ExprKind::{Field, Index, Path};
725
726     match e.kind {
727         Path(ref qpath) => !matches!(qpath_res(cx, qpath, e.hir_id), Res::Local(_)),
728         Field(ref inner, _) | Index(ref inner, _) => is_mutated_static(cx, inner),
729         _ => false,
730     }
731 }
732
733 fn mutates_static<'tcx>(cx: &LateContext<'tcx>, body: &'tcx hir::Body<'_>) -> bool {
734     let mut v = StaticMutVisitor {
735         cx,
736         mutates_static: false,
737     };
738     intravisit::walk_expr(&mut v, &body.value);
739     v.mutates_static
740 }