]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/functions.rs
Auto merge of #4849 - flip1995:deny_warnings, r=phansch
[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::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::FnSig {
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 sig, ref _generics, ref body_id) = item.kind {
232             if let Some(attr) = attr {
233                 let fn_header_span = item.span.with_hi(sig.decl.output.span().hi());
234                 check_needless_must_use(cx, &sig.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                     &sig.decl,
241                     cx.tcx.hir().body(*body_id),
242                     item.span,
243                     item.hir_id,
244                     item.span.with_hi(sig.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)
258                 && !is_proc_macro(&item.attrs)
259                 && trait_ref_of_method(cx, item.hir_id).is_none()
260             {
261                 check_must_use_candidate(
262                     cx,
263                     &sig.decl,
264                     cx.tcx.hir().body(*body_id),
265                     item.span,
266                     item.hir_id,
267                     item.span.with_hi(sig.decl.output.span().hi()),
268                     "this method could have a `#[must_use]` attribute",
269                 );
270             }
271         }
272     }
273
274     fn check_trait_item(&mut self, cx: &LateContext<'a, 'tcx>, item: &'tcx hir::TraitItem) {
275         if let hir::TraitItemKind::Method(ref sig, ref eid) = item.kind {
276             // don't lint extern functions decls, it's not their fault
277             if sig.header.abi == Abi::Rust {
278                 self.check_arg_number(cx, &sig.decl, item.span.with_hi(sig.decl.output.span().hi()));
279             }
280
281             let attr = must_use_attr(&item.attrs);
282             if let Some(attr) = attr {
283                 let fn_header_span = item.span.with_hi(sig.decl.output.span().hi());
284                 check_needless_must_use(cx, &sig.decl, item.hir_id, item.span, fn_header_span, attr);
285             }
286             if let hir::TraitMethod::Provided(eid) = *eid {
287                 let body = cx.tcx.hir().body(eid);
288                 Self::check_raw_ptr(cx, sig.header.unsafety, &sig.decl, body, item.hir_id);
289
290                 if attr.is_none() && cx.access_levels.is_exported(item.hir_id) && !is_proc_macro(&item.attrs) {
291                     check_must_use_candidate(
292                         cx,
293                         &sig.decl,
294                         body,
295                         item.span,
296                         item.hir_id,
297                         item.span.with_hi(sig.decl.output.span().hi()),
298                         "this method could have a `#[must_use]` attribute",
299                     );
300                 }
301             }
302         }
303     }
304 }
305
306 impl<'a, 'tcx> Functions {
307     fn check_arg_number(self, cx: &LateContext<'_, '_>, decl: &hir::FnDecl, fn_span: Span) {
308         let args = decl.inputs.len() as u64;
309         if args > self.threshold {
310             span_lint(
311                 cx,
312                 TOO_MANY_ARGUMENTS,
313                 fn_span,
314                 &format!("this function has too many arguments ({}/{})", args, self.threshold),
315             );
316         }
317     }
318
319     fn check_line_number(self, cx: &LateContext<'_, '_>, span: Span, body: &'tcx hir::Body) {
320         if in_external_macro(cx.sess(), span) {
321             return;
322         }
323
324         let code_snippet = snippet(cx, body.value.span, "..");
325         let mut line_count: u64 = 0;
326         let mut in_comment = false;
327         let mut code_in_line;
328
329         // Skip the surrounding function decl.
330         let start_brace_idx = code_snippet.find('{').map_or(0, |i| i + 1);
331         let end_brace_idx = code_snippet.rfind('}').unwrap_or_else(|| code_snippet.len());
332         let function_lines = code_snippet[start_brace_idx..end_brace_idx].lines();
333
334         for mut line in function_lines {
335             code_in_line = false;
336             loop {
337                 line = line.trim_start();
338                 if line.is_empty() {
339                     break;
340                 }
341                 if in_comment {
342                     match line.find("*/") {
343                         Some(i) => {
344                             line = &line[i + 2..];
345                             in_comment = false;
346                             continue;
347                         },
348                         None => break,
349                     }
350                 } else {
351                     let multi_idx = line.find("/*").unwrap_or_else(|| line.len());
352                     let single_idx = line.find("//").unwrap_or_else(|| line.len());
353                     code_in_line |= multi_idx > 0 && single_idx > 0;
354                     // Implies multi_idx is below line.len()
355                     if multi_idx < single_idx {
356                         line = &line[multi_idx + 2..];
357                         in_comment = true;
358                         continue;
359                     }
360                     break;
361                 }
362             }
363             if code_in_line {
364                 line_count += 1;
365             }
366         }
367
368         if line_count > self.max_lines {
369             span_lint(cx, TOO_MANY_LINES, span, "This function has a large number of lines.")
370         }
371     }
372
373     fn check_raw_ptr(
374         cx: &LateContext<'a, 'tcx>,
375         unsafety: hir::Unsafety,
376         decl: &'tcx hir::FnDecl,
377         body: &'tcx hir::Body,
378         hir_id: hir::HirId,
379     ) {
380         let expr = &body.value;
381         if unsafety == hir::Unsafety::Normal && cx.access_levels.is_exported(hir_id) {
382             let raw_ptrs = iter_input_pats(decl, body)
383                 .zip(decl.inputs.iter())
384                 .filter_map(|(arg, ty)| raw_ptr_arg(arg, ty))
385                 .collect::<FxHashSet<_>>();
386
387             if !raw_ptrs.is_empty() {
388                 let tables = cx.tcx.body_tables(body.id());
389                 let mut v = DerefVisitor {
390                     cx,
391                     ptrs: raw_ptrs,
392                     tables,
393                 };
394
395                 hir::intravisit::walk_expr(&mut v, expr);
396             }
397         }
398     }
399 }
400
401 fn check_needless_must_use(
402     cx: &LateContext<'_, '_>,
403     decl: &hir::FnDecl,
404     item_id: hir::HirId,
405     item_span: Span,
406     fn_header_span: Span,
407     attr: &Attribute,
408 ) {
409     if in_external_macro(cx.sess(), item_span) {
410         return;
411     }
412     if returns_unit(decl) {
413         span_lint_and_then(
414             cx,
415             MUST_USE_UNIT,
416             fn_header_span,
417             "this unit-returning function has a `#[must_use]` attribute",
418             |db| {
419                 db.span_suggestion(
420                     attr.span,
421                     "remove the attribute",
422                     "".into(),
423                     Applicability::MachineApplicable,
424                 );
425             },
426         );
427     } else if !attr.is_value_str() && is_must_use_ty(cx, return_ty(cx, item_id)) {
428         span_help_and_lint(
429             cx,
430             DOUBLE_MUST_USE,
431             fn_header_span,
432             "this function has an empty `#[must_use]` attribute, but returns a type already marked as `#[must_use]`",
433             "either add some descriptive text or remove the attribute",
434         );
435     }
436 }
437
438 fn check_must_use_candidate<'a, 'tcx>(
439     cx: &LateContext<'a, 'tcx>,
440     decl: &'tcx hir::FnDecl,
441     body: &'tcx hir::Body,
442     item_span: Span,
443     item_id: hir::HirId,
444     fn_span: Span,
445     msg: &str,
446 ) {
447     if has_mutable_arg(cx, body)
448         || mutates_static(cx, body)
449         || in_external_macro(cx.sess(), item_span)
450         || returns_unit(decl)
451         || is_must_use_ty(cx, return_ty(cx, item_id))
452     {
453         return;
454     }
455     span_lint_and_then(cx, MUST_USE_CANDIDATE, fn_span, msg, |db| {
456         if let Some(snippet) = snippet_opt(cx, fn_span) {
457             db.span_suggestion(
458                 fn_span,
459                 "add the attribute",
460                 format!("#[must_use] {}", snippet),
461                 Applicability::MachineApplicable,
462             );
463         }
464     });
465 }
466
467 fn must_use_attr(attrs: &[Attribute]) -> Option<&Attribute> {
468     attrs.iter().find(|attr| {
469         attr.ident().map_or(false, |ident| {
470             let ident: &str = &ident.as_str();
471             "must_use" == ident
472         })
473     })
474 }
475
476 fn returns_unit(decl: &hir::FnDecl) -> bool {
477     match decl.output {
478         hir::FunctionRetTy::DefaultReturn(_) => true,
479         hir::FunctionRetTy::Return(ref ty) => match ty.kind {
480             hir::TyKind::Tup(ref tys) => tys.is_empty(),
481             hir::TyKind::Never => true,
482             _ => false,
483         },
484     }
485 }
486
487 fn is_must_use_ty<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, ty: Ty<'tcx>) -> bool {
488     use ty::TyKind::*;
489     match ty.kind {
490         Adt(ref adt, _) => must_use_attr(&cx.tcx.get_attrs(adt.did)).is_some(),
491         Foreign(ref did) => must_use_attr(&cx.tcx.get_attrs(*did)).is_some(),
492         Slice(ref ty) | Array(ref ty, _) | RawPtr(ty::TypeAndMut { ref ty, .. }) | Ref(_, ref ty, _) => {
493             // for the Array case we don't need to care for the len == 0 case
494             // because we don't want to lint functions returning empty arrays
495             is_must_use_ty(cx, *ty)
496         },
497         Tuple(ref substs) => substs.types().any(|ty| is_must_use_ty(cx, ty)),
498         Opaque(ref def_id, _) => {
499             for (predicate, _) in cx.tcx.predicates_of(*def_id).predicates {
500                 if let ty::Predicate::Trait(ref poly_trait_predicate) = predicate {
501                     if must_use_attr(&cx.tcx.get_attrs(poly_trait_predicate.skip_binder().trait_ref.def_id)).is_some() {
502                         return true;
503                     }
504                 }
505             }
506             false
507         },
508         Dynamic(binder, _) => {
509             for predicate in binder.skip_binder().iter() {
510                 if let ty::ExistentialPredicate::Trait(ref trait_ref) = predicate {
511                     if must_use_attr(&cx.tcx.get_attrs(trait_ref.def_id)).is_some() {
512                         return true;
513                     }
514                 }
515             }
516             false
517         },
518         _ => false,
519     }
520 }
521
522 fn has_mutable_arg(cx: &LateContext<'_, '_>, body: &hir::Body) -> bool {
523     let mut tys = FxHashSet::default();
524     body.params.iter().any(|param| is_mutable_pat(cx, &param.pat, &mut tys))
525 }
526
527 fn is_mutable_pat(cx: &LateContext<'_, '_>, pat: &hir::Pat, tys: &mut FxHashSet<DefId>) -> bool {
528     if let hir::PatKind::Wild = pat.kind {
529         return false; // ignore `_` patterns
530     }
531     let def_id = pat.hir_id.owner_def_id();
532     if cx.tcx.has_typeck_tables(def_id) {
533         is_mutable_ty(cx, &cx.tcx.typeck_tables_of(def_id).pat_ty(pat), pat.span, tys)
534     } else {
535         false
536     }
537 }
538
539 static KNOWN_WRAPPER_TYS: &[&[&str]] = &[&["alloc", "rc", "Rc"], &["std", "sync", "Arc"]];
540
541 fn is_mutable_ty<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, ty: Ty<'tcx>, span: Span, tys: &mut FxHashSet<DefId>) -> bool {
542     use ty::TyKind::*;
543     match ty.kind {
544         // primitive types are never mutable
545         Bool | Char | Int(_) | Uint(_) | Float(_) | Str => false,
546         Adt(ref adt, ref substs) => {
547             tys.insert(adt.did) && !ty.is_freeze(cx.tcx, cx.param_env, span)
548                 || KNOWN_WRAPPER_TYS.iter().any(|path| match_def_path(cx, adt.did, path))
549                     && substs.types().any(|ty| is_mutable_ty(cx, ty, span, tys))
550         },
551         Tuple(ref substs) => substs.types().any(|ty| is_mutable_ty(cx, ty, span, tys)),
552         Array(ty, _) | Slice(ty) => is_mutable_ty(cx, ty, span, tys),
553         RawPtr(ty::TypeAndMut { ty, mutbl }) | Ref(_, ty, mutbl) => {
554             mutbl == hir::Mutability::Mutable || is_mutable_ty(cx, ty, span, tys)
555         },
556         // calling something constitutes a side effect, so return true on all callables
557         // also never calls need not be used, so return true for them, too
558         _ => true,
559     }
560 }
561
562 fn raw_ptr_arg(arg: &hir::Param, ty: &hir::Ty) -> Option<hir::HirId> {
563     if let (&hir::PatKind::Binding(_, id, _, _), &hir::TyKind::Ptr(_)) = (&arg.pat.kind, &ty.kind) {
564         Some(id)
565     } else {
566         None
567     }
568 }
569
570 struct DerefVisitor<'a, 'tcx> {
571     cx: &'a LateContext<'a, 'tcx>,
572     ptrs: FxHashSet<hir::HirId>,
573     tables: &'a ty::TypeckTables<'tcx>,
574 }
575
576 impl<'a, 'tcx> intravisit::Visitor<'tcx> for DerefVisitor<'a, 'tcx> {
577     fn visit_expr(&mut self, expr: &'tcx hir::Expr) {
578         match expr.kind {
579             hir::ExprKind::Call(ref f, ref args) => {
580                 let ty = self.tables.expr_ty(f);
581
582                 if type_is_unsafe_function(self.cx, ty) {
583                     for arg in args {
584                         self.check_arg(arg);
585                     }
586                 }
587             },
588             hir::ExprKind::MethodCall(_, _, ref args) => {
589                 let def_id = self.tables.type_dependent_def_id(expr.hir_id).unwrap();
590                 let base_type = self.cx.tcx.type_of(def_id);
591
592                 if type_is_unsafe_function(self.cx, base_type) {
593                     for arg in args {
594                         self.check_arg(arg);
595                     }
596                 }
597             },
598             hir::ExprKind::Unary(hir::UnDeref, ref ptr) => self.check_arg(ptr),
599             _ => (),
600         }
601
602         intravisit::walk_expr(self, expr);
603     }
604
605     fn nested_visit_map<'this>(&'this mut self) -> intravisit::NestedVisitorMap<'this, 'tcx> {
606         intravisit::NestedVisitorMap::None
607     }
608 }
609
610 impl<'a, 'tcx> DerefVisitor<'a, 'tcx> {
611     fn check_arg(&self, ptr: &hir::Expr) {
612         if let hir::ExprKind::Path(ref qpath) = ptr.kind {
613             if let Res::Local(id) = qpath_res(self.cx, qpath, ptr.hir_id) {
614                 if self.ptrs.contains(&id) {
615                     span_lint(
616                         self.cx,
617                         NOT_UNSAFE_PTR_ARG_DEREF,
618                         ptr.span,
619                         "this public function dereferences a raw pointer but is not marked `unsafe`",
620                     );
621                 }
622             }
623         }
624     }
625 }
626
627 struct StaticMutVisitor<'a, 'tcx> {
628     cx: &'a LateContext<'a, 'tcx>,
629     mutates_static: bool,
630 }
631
632 impl<'a, 'tcx> intravisit::Visitor<'tcx> for StaticMutVisitor<'a, 'tcx> {
633     fn visit_expr(&mut self, expr: &'tcx hir::Expr) {
634         use hir::ExprKind::*;
635
636         if self.mutates_static {
637             return;
638         }
639         match expr.kind {
640             Call(_, ref args) | MethodCall(_, _, ref args) => {
641                 let mut tys = FxHashSet::default();
642                 for arg in args {
643                     let def_id = arg.hir_id.owner_def_id();
644                     if self.cx.tcx.has_typeck_tables(def_id)
645                         && is_mutable_ty(
646                             self.cx,
647                             self.cx.tcx.typeck_tables_of(def_id).expr_ty(arg),
648                             arg.span,
649                             &mut tys,
650                         )
651                         && is_mutated_static(self.cx, arg)
652                     {
653                         self.mutates_static = true;
654                         return;
655                     }
656                     tys.clear();
657                 }
658             },
659             Assign(ref target, _) | AssignOp(_, ref target, _) | AddrOf(_, hir::Mutability::Mutable, ref target) => {
660                 self.mutates_static |= is_mutated_static(self.cx, target)
661             },
662             _ => {},
663         }
664     }
665
666     fn nested_visit_map<'this>(&'this mut self) -> intravisit::NestedVisitorMap<'this, 'tcx> {
667         intravisit::NestedVisitorMap::None
668     }
669 }
670
671 fn is_mutated_static(cx: &LateContext<'_, '_>, e: &hir::Expr) -> bool {
672     use hir::ExprKind::*;
673
674     match e.kind {
675         Path(ref qpath) => {
676             if let Res::Local(_) = qpath_res(cx, qpath, e.hir_id) {
677                 false
678             } else {
679                 true
680             }
681         },
682         Field(ref inner, _) | Index(ref inner, _) => is_mutated_static(cx, inner),
683         _ => false,
684     }
685 }
686
687 fn mutates_static<'a, 'tcx>(cx: &'a LateContext<'a, 'tcx>, body: &'tcx hir::Body) -> bool {
688     let mut v = StaticMutVisitor {
689         cx,
690         mutates_static: false,
691     };
692     intravisit::walk_expr(&mut v, &body.value);
693     v.mutates_static
694 }