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