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