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