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