]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/functions.rs
Merge remote-tracking branch 'upstream/master' into rustup
[rust.git] / clippy_lints / src / functions.rs
1 use crate::utils::{
2     attr_by_name, attrs::is_proc_macro, is_must_use_ty, is_trait_impl_item, iter_input_pats, match_def_path,
3     must_use_attr, qpath_res, return_ty, snippet, snippet_opt, span_lint, span_lint_and_help, span_lint_and_then,
4     trait_ref_of_method, type_is_unsafe_function,
5 };
6 use rustc_ast::ast::Attribute;
7 use rustc_data_structures::fx::FxHashSet;
8 use rustc_errors::Applicability;
9 use rustc_hir as hir;
10 use rustc_hir::intravisit;
11 use rustc_hir::{def::Res, def_id::DefId};
12 use rustc_lint::{LateContext, LateLintPass, LintContext};
13 use rustc_middle::hir::map::Map;
14 use rustc_middle::lint::in_external_macro;
15 use rustc_middle::ty::{self, Ty};
16 use rustc_session::{declare_tool_lint, impl_lint_pass};
17 use rustc_span::source_map::Span;
18 use rustc_target::spec::abi::Abi;
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,ignore
83     /// // Bad
84     /// pub fn foo(x: *const u8) {
85     ///     println!("{}", unsafe { *x });
86     /// }
87     ///
88     /// // Good
89     /// pub unsafe fn foo(x: *const u8) {
90     ///     println!("{}", unsafe { *x });
91     /// }
92     /// ```
93     pub NOT_UNSAFE_PTR_ARG_DEREF,
94     correctness,
95     "public functions dereferencing raw pointer arguments but not marked `unsafe`"
96 }
97
98 declare_clippy_lint! {
99     /// **What it does:** Checks for a [`#[must_use]`] attribute on
100     /// unit-returning functions and methods.
101     ///
102     /// [`#[must_use]`]: https://doc.rust-lang.org/reference/attributes/diagnostics.html#the-must_use-attribute
103     ///
104     /// **Why is this bad?** Unit values are useless. The attribute is likely
105     /// a remnant of a refactoring that removed the return type.
106     ///
107     /// **Known problems:** None.
108     ///
109     /// **Examples:**
110     /// ```rust
111     /// #[must_use]
112     /// fn useless() { }
113     /// ```
114     pub MUST_USE_UNIT,
115     style,
116     "`#[must_use]` attribute on a unit-returning function / method"
117 }
118
119 declare_clippy_lint! {
120     /// **What it does:** Checks for a [`#[must_use]`] attribute without
121     /// further information on functions and methods that return a type already
122     /// marked as `#[must_use]`.
123     ///
124     /// [`#[must_use]`]: https://doc.rust-lang.org/reference/attributes/diagnostics.html#the-must_use-attribute
125     ///
126     /// **Why is this bad?** The attribute isn't needed. Not using the result
127     /// will already be reported. Alternatively, one can add some text to the
128     /// attribute to improve the lint message.
129     ///
130     /// **Known problems:** None.
131     ///
132     /// **Examples:**
133     /// ```rust
134     /// #[must_use]
135     /// fn double_must_use() -> Result<(), ()> {
136     ///     unimplemented!();
137     /// }
138     /// ```
139     pub DOUBLE_MUST_USE,
140     style,
141     "`#[must_use]` attribute on a `#[must_use]`-returning function / method"
142 }
143
144 declare_clippy_lint! {
145     /// **What it does:** Checks for public functions that have no
146     /// [`#[must_use]`] attribute, but return something not already marked
147     /// must-use, have no mutable arg and mutate no statics.
148     ///
149     /// [`#[must_use]`]: https://doc.rust-lang.org/reference/attributes/diagnostics.html#the-must_use-attribute
150     ///
151     /// **Why is this bad?** Not bad at all, this lint just shows places where
152     /// you could add the attribute.
153     ///
154     /// **Known problems:** The lint only checks the arguments for mutable
155     /// types without looking if they are actually changed. On the other hand,
156     /// it also ignores a broad range of potentially interesting side effects,
157     /// because we cannot decide whether the programmer intends the function to
158     /// be called for the side effect or the result. Expect many false
159     /// positives. At least we don't lint if the result type is unit or already
160     /// `#[must_use]`.
161     ///
162     /// **Examples:**
163     /// ```rust
164     /// // this could be annotated with `#[must_use]`.
165     /// fn id<T>(t: T) -> T { t }
166     /// ```
167     pub MUST_USE_CANDIDATE,
168     pedantic,
169     "function or method that could take a `#[must_use]` attribute"
170 }
171
172 #[derive(Copy, Clone)]
173 pub struct Functions {
174     threshold: u64,
175     max_lines: u64,
176 }
177
178 impl Functions {
179     pub fn new(threshold: u64, max_lines: u64) -> Self {
180         Self { threshold, max_lines }
181     }
182 }
183
184 impl_lint_pass!(Functions => [
185     TOO_MANY_ARGUMENTS,
186     TOO_MANY_LINES,
187     NOT_UNSAFE_PTR_ARG_DEREF,
188     MUST_USE_UNIT,
189     DOUBLE_MUST_USE,
190     MUST_USE_CANDIDATE,
191 ]);
192
193 impl<'tcx> LateLintPass<'tcx> for Functions {
194     fn check_fn(
195         &mut self,
196         cx: &LateContext<'tcx>,
197         kind: intravisit::FnKind<'tcx>,
198         decl: &'tcx hir::FnDecl<'_>,
199         body: &'tcx hir::Body<'_>,
200         span: Span,
201         hir_id: hir::HirId,
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_trait_impl_item(cx, hir_id) {
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<'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(cx.sess(), &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<'tcx>, item: &'tcx hir::ImplItem<'_>) {
259         if let hir::ImplItemKind::Fn(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(cx.sess(), &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<'tcx>, item: &'tcx hir::TraitItem<'_>) {
282         if let hir::TraitItemKind::Fn(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::TraitFn::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(cx.sess(), &item.attrs)
298                 {
299                     check_must_use_candidate(
300                         cx,
301                         &sig.decl,
302                         body,
303                         item.span,
304                         item.hir_id,
305                         item.span.with_hi(sig.decl.output.span().hi()),
306                         "this method could have a `#[must_use]` attribute",
307                     );
308                 }
309             }
310         }
311     }
312 }
313
314 impl<'tcx> Functions {
315     fn check_arg_number(self, cx: &LateContext<'_>, decl: &hir::FnDecl<'_>, fn_span: Span) {
316         let args = decl.inputs.len() as u64;
317         if args > self.threshold {
318             span_lint(
319                 cx,
320                 TOO_MANY_ARGUMENTS,
321                 fn_span,
322                 &format!("this function has too many arguments ({}/{})", args, self.threshold),
323             );
324         }
325     }
326
327     fn check_line_number(self, cx: &LateContext<'_>, span: Span, body: &'tcx hir::Body<'_>) {
328         if in_external_macro(cx.sess(), span) {
329             return;
330         }
331
332         let code_snippet = snippet(cx, body.value.span, "..");
333         let mut line_count: u64 = 0;
334         let mut in_comment = false;
335         let mut code_in_line;
336
337         // Skip the surrounding function decl.
338         let start_brace_idx = code_snippet.find('{').map_or(0, |i| i + 1);
339         let end_brace_idx = code_snippet.rfind('}').unwrap_or_else(|| code_snippet.len());
340         let function_lines = code_snippet[start_brace_idx..end_brace_idx].lines();
341
342         for mut line in function_lines {
343             code_in_line = false;
344             loop {
345                 line = line.trim_start();
346                 if line.is_empty() {
347                     break;
348                 }
349                 if in_comment {
350                     match line.find("*/") {
351                         Some(i) => {
352                             line = &line[i + 2..];
353                             in_comment = false;
354                             continue;
355                         },
356                         None => break,
357                     }
358                 } else {
359                     let multi_idx = line.find("/*").unwrap_or_else(|| line.len());
360                     let single_idx = line.find("//").unwrap_or_else(|| line.len());
361                     code_in_line |= multi_idx > 0 && single_idx > 0;
362                     // Implies multi_idx is below line.len()
363                     if multi_idx < single_idx {
364                         line = &line[multi_idx + 2..];
365                         in_comment = true;
366                         continue;
367                     }
368                     break;
369                 }
370             }
371             if code_in_line {
372                 line_count += 1;
373             }
374         }
375
376         if line_count > self.max_lines {
377             span_lint(
378                 cx,
379                 TOO_MANY_LINES,
380                 span,
381                 &format!("this function has too many lines ({}/{})", line_count, self.max_lines),
382             )
383         }
384     }
385
386     fn check_raw_ptr(
387         cx: &LateContext<'tcx>,
388         unsafety: hir::Unsafety,
389         decl: &'tcx hir::FnDecl<'_>,
390         body: &'tcx hir::Body<'_>,
391         hir_id: hir::HirId,
392     ) {
393         let expr = &body.value;
394         if unsafety == hir::Unsafety::Normal && cx.access_levels.is_exported(hir_id) {
395             let raw_ptrs = iter_input_pats(decl, body)
396                 .zip(decl.inputs.iter())
397                 .filter_map(|(arg, ty)| raw_ptr_arg(arg, ty))
398                 .collect::<FxHashSet<_>>();
399
400             if !raw_ptrs.is_empty() {
401                 let typeck_results = cx.tcx.typeck_body(body.id());
402                 let mut v = DerefVisitor {
403                     cx,
404                     ptrs: raw_ptrs,
405                     typeck_results,
406                 };
407
408                 intravisit::walk_expr(&mut v, expr);
409             }
410         }
411     }
412 }
413
414 fn check_needless_must_use(
415     cx: &LateContext<'_>,
416     decl: &hir::FnDecl<'_>,
417     item_id: hir::HirId,
418     item_span: Span,
419     fn_header_span: Span,
420     attr: &Attribute,
421 ) {
422     if in_external_macro(cx.sess(), item_span) {
423         return;
424     }
425     if returns_unit(decl) {
426         span_lint_and_then(
427             cx,
428             MUST_USE_UNIT,
429             fn_header_span,
430             "this unit-returning function has a `#[must_use]` attribute",
431             |diag| {
432                 diag.span_suggestion(
433                     attr.span,
434                     "remove the attribute",
435                     "".into(),
436                     Applicability::MachineApplicable,
437                 );
438             },
439         );
440     } else if !attr.is_value_str() && is_must_use_ty(cx, return_ty(cx, item_id)) {
441         span_lint_and_help(
442             cx,
443             DOUBLE_MUST_USE,
444             fn_header_span,
445             "this function has an empty `#[must_use]` attribute, but returns a type already marked as `#[must_use]`",
446             None,
447             "either add some descriptive text or remove the attribute",
448         );
449     }
450 }
451
452 fn check_must_use_candidate<'tcx>(
453     cx: &LateContext<'tcx>,
454     decl: &'tcx hir::FnDecl<'_>,
455     body: &'tcx hir::Body<'_>,
456     item_span: Span,
457     item_id: hir::HirId,
458     fn_span: Span,
459     msg: &str,
460 ) {
461     if has_mutable_arg(cx, body)
462         || mutates_static(cx, body)
463         || in_external_macro(cx.sess(), item_span)
464         || returns_unit(decl)
465         || !cx.access_levels.is_exported(item_id)
466         || is_must_use_ty(cx, return_ty(cx, item_id))
467     {
468         return;
469     }
470     span_lint_and_then(cx, MUST_USE_CANDIDATE, fn_span, msg, |diag| {
471         if let Some(snippet) = snippet_opt(cx, fn_span) {
472             diag.span_suggestion(
473                 fn_span,
474                 "add the attribute",
475                 format!("#[must_use] {}", snippet),
476                 Applicability::MachineApplicable,
477             );
478         }
479     });
480 }
481
482 fn returns_unit(decl: &hir::FnDecl<'_>) -> bool {
483     match decl.output {
484         hir::FnRetTy::DefaultReturn(_) => true,
485         hir::FnRetTy::Return(ref ty) => match ty.kind {
486             hir::TyKind::Tup(ref tys) => tys.is_empty(),
487             hir::TyKind::Never => true,
488             _ => false,
489         },
490     }
491 }
492
493 fn has_mutable_arg(cx: &LateContext<'_>, body: &hir::Body<'_>) -> bool {
494     let mut tys = FxHashSet::default();
495     body.params.iter().any(|param| is_mutable_pat(cx, &param.pat, &mut tys))
496 }
497
498 fn is_mutable_pat(cx: &LateContext<'_>, pat: &hir::Pat<'_>, tys: &mut FxHashSet<DefId>) -> bool {
499     if let hir::PatKind::Wild = pat.kind {
500         return false; // ignore `_` patterns
501     }
502     let def_id = pat.hir_id.owner.to_def_id();
503     if cx.tcx.has_typeck_results(def_id) {
504         is_mutable_ty(cx, &cx.tcx.typeck(def_id.expect_local()).pat_ty(pat), pat.span, tys)
505     } else {
506         false
507     }
508 }
509
510 static KNOWN_WRAPPER_TYS: &[&[&str]] = &[&["alloc", "rc", "Rc"], &["std", "sync", "Arc"]];
511
512 fn is_mutable_ty<'tcx>(cx: &LateContext<'tcx>, ty: Ty<'tcx>, span: Span, tys: &mut FxHashSet<DefId>) -> bool {
513     match *ty.kind() {
514         // primitive types are never mutable
515         ty::Bool | ty::Char | ty::Int(_) | ty::Uint(_) | ty::Float(_) | ty::Str => false,
516         ty::Adt(ref adt, ref substs) => {
517             tys.insert(adt.did) && !ty.is_freeze(cx.tcx.at(span), cx.param_env)
518                 || KNOWN_WRAPPER_TYS.iter().any(|path| match_def_path(cx, adt.did, path))
519                     && substs.types().any(|ty| is_mutable_ty(cx, ty, span, tys))
520         },
521         ty::Tuple(ref substs) => substs.types().any(|ty| is_mutable_ty(cx, ty, span, tys)),
522         ty::Array(ty, _) | ty::Slice(ty) => is_mutable_ty(cx, ty, span, tys),
523         ty::RawPtr(ty::TypeAndMut { ty, mutbl }) | ty::Ref(_, ty, mutbl) => {
524             mutbl == hir::Mutability::Mut || is_mutable_ty(cx, ty, span, tys)
525         },
526         // calling something constitutes a side effect, so return true on all callables
527         // also never calls need not be used, so return true for them, too
528         _ => true,
529     }
530 }
531
532 fn raw_ptr_arg(arg: &hir::Param<'_>, ty: &hir::Ty<'_>) -> Option<hir::HirId> {
533     if let (&hir::PatKind::Binding(_, id, _, _), &hir::TyKind::Ptr(_)) = (&arg.pat.kind, &ty.kind) {
534         Some(id)
535     } else {
536         None
537     }
538 }
539
540 struct DerefVisitor<'a, 'tcx> {
541     cx: &'a LateContext<'tcx>,
542     ptrs: FxHashSet<hir::HirId>,
543     typeck_results: &'a ty::TypeckResults<'tcx>,
544 }
545
546 impl<'a, 'tcx> intravisit::Visitor<'tcx> for DerefVisitor<'a, 'tcx> {
547     type Map = Map<'tcx>;
548
549     fn visit_expr(&mut self, expr: &'tcx hir::Expr<'_>) {
550         match expr.kind {
551             hir::ExprKind::Call(ref f, args) => {
552                 let ty = self.typeck_results.expr_ty(f);
553
554                 if type_is_unsafe_function(self.cx, ty) {
555                     for arg in args {
556                         self.check_arg(arg);
557                     }
558                 }
559             },
560             hir::ExprKind::MethodCall(_, _, args, _) => {
561                 let def_id = self.typeck_results.type_dependent_def_id(expr.hir_id).unwrap();
562                 let base_type = self.cx.tcx.type_of(def_id);
563
564                 if type_is_unsafe_function(self.cx, base_type) {
565                     for arg in args {
566                         self.check_arg(arg);
567                     }
568                 }
569             },
570             hir::ExprKind::Unary(hir::UnOp::UnDeref, ref ptr) => self.check_arg(ptr),
571             _ => (),
572         }
573
574         intravisit::walk_expr(self, expr);
575     }
576
577     fn nested_visit_map(&mut self) -> intravisit::NestedVisitorMap<Self::Map> {
578         intravisit::NestedVisitorMap::None
579     }
580 }
581
582 impl<'a, 'tcx> DerefVisitor<'a, 'tcx> {
583     fn check_arg(&self, ptr: &hir::Expr<'_>) {
584         if let hir::ExprKind::Path(ref qpath) = ptr.kind {
585             if let Res::Local(id) = qpath_res(self.cx, qpath, ptr.hir_id) {
586                 if self.ptrs.contains(&id) {
587                     span_lint(
588                         self.cx,
589                         NOT_UNSAFE_PTR_ARG_DEREF,
590                         ptr.span,
591                         "this public function dereferences a raw pointer but is not marked `unsafe`",
592                     );
593                 }
594             }
595         }
596     }
597 }
598
599 struct StaticMutVisitor<'a, 'tcx> {
600     cx: &'a LateContext<'tcx>,
601     mutates_static: bool,
602 }
603
604 impl<'a, 'tcx> intravisit::Visitor<'tcx> for StaticMutVisitor<'a, 'tcx> {
605     type Map = Map<'tcx>;
606
607     fn visit_expr(&mut self, expr: &'tcx hir::Expr<'_>) {
608         use hir::ExprKind::{AddrOf, Assign, AssignOp, Call, MethodCall};
609
610         if self.mutates_static {
611             return;
612         }
613         match expr.kind {
614             Call(_, args) | MethodCall(_, _, args, _) => {
615                 let mut tys = FxHashSet::default();
616                 for arg in args {
617                     let def_id = arg.hir_id.owner.to_def_id();
618                     if self.cx.tcx.has_typeck_results(def_id)
619                         && is_mutable_ty(
620                             self.cx,
621                             self.cx.tcx.typeck(def_id.expect_local()).expr_ty(arg),
622                             arg.span,
623                             &mut tys,
624                         )
625                         && is_mutated_static(self.cx, arg)
626                     {
627                         self.mutates_static = true;
628                         return;
629                     }
630                     tys.clear();
631                 }
632             },
633             Assign(ref target, ..) | AssignOp(_, ref target, _) | AddrOf(_, hir::Mutability::Mut, ref target) => {
634                 self.mutates_static |= is_mutated_static(self.cx, target)
635             },
636             _ => {},
637         }
638     }
639
640     fn nested_visit_map(&mut self) -> intravisit::NestedVisitorMap<Self::Map> {
641         intravisit::NestedVisitorMap::None
642     }
643 }
644
645 fn is_mutated_static(cx: &LateContext<'_>, e: &hir::Expr<'_>) -> bool {
646     use hir::ExprKind::{Field, Index, Path};
647
648     match e.kind {
649         Path(ref qpath) => !matches!(qpath_res(cx, qpath, e.hir_id), Res::Local(_)),
650         Field(ref inner, _) | Index(ref inner, _) => is_mutated_static(cx, inner),
651         _ => false,
652     }
653 }
654
655 fn mutates_static<'tcx>(cx: &LateContext<'tcx>, body: &'tcx hir::Body<'_>) -> bool {
656     let mut v = StaticMutVisitor {
657         cx,
658         mutates_static: false,
659     };
660     intravisit::walk_expr(&mut v, &body.value);
661     v.mutates_static
662 }