]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/utils/mod.rs
6e81f3d0199661650e06b01e90fa68bbc73a8774
[rust.git] / clippy_lints / src / utils / mod.rs
1 // Copyright 2014-2018 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution.
3 //
4 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
5 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
6 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
7 // option. This file may not be copied, modified, or distributed
8 // except according to those terms.
9
10
11 use crate::reexport::*;
12 use matches::matches;
13 use if_chain::if_chain;
14 use crate::rustc::hir;
15 use crate::rustc::hir::*;
16 use crate::rustc::hir::def_id::{DefId, CRATE_DEF_INDEX};
17 use crate::rustc::hir::def::Def;
18 use crate::rustc::hir::intravisit::{NestedVisitorMap, Visitor};
19 use crate::rustc::hir::Node;
20 use crate::rustc::lint::{LateContext, Level, Lint, LintContext};
21 use crate::rustc::session::Session;
22 use crate::rustc::traits;
23 use crate::rustc::ty::{self, Binder, Ty, TyCtxt, layout::{self, IntegerExt}, subst::Kind};
24 use crate::rustc_errors::{Applicability, CodeSuggestion, Substitution, SubstitutionPart};
25 use std::borrow::Cow;
26 use std::env;
27 use std::mem;
28 use std::str::FromStr;
29 use std::rc::Rc;
30 use crate::syntax::ast::{self, LitKind};
31 use crate::syntax::attr;
32 use crate::syntax::source_map::{Span, DUMMY_SP};
33 use crate::syntax::errors::DiagnosticBuilder;
34 use crate::syntax::symbol::{keywords, Symbol};
35
36 pub mod camel_case;
37
38 pub mod comparisons;
39 pub mod conf;
40 pub mod constants;
41 mod hir_utils;
42 pub mod paths;
43 pub mod sugg;
44 pub mod inspector;
45 pub mod internal_lints;
46 pub mod author;
47 pub mod ptr;
48 pub mod usage;
49 pub use self::hir_utils::{SpanlessEq, SpanlessHash};
50
51 pub mod higher;
52
53 /// Returns true if the two spans come from differing expansions (i.e. one is
54 /// from a macro and one
55 /// isn't).
56 pub fn differing_macro_contexts(lhs: Span, rhs: Span) -> bool {
57     rhs.ctxt() != lhs.ctxt()
58 }
59
60 pub fn in_constant(cx: &LateContext<'_, '_>, id: NodeId) -> bool {
61     let parent_id = cx.tcx.hir.get_parent(id);
62     match cx.tcx.hir.body_owner_kind(parent_id) {
63         hir::BodyOwnerKind::Fn => false,
64         hir::BodyOwnerKind::Const | hir::BodyOwnerKind::Static(..) => true,
65     }
66 }
67
68 /// Returns true if this `expn_info` was expanded by any macro.
69 pub fn in_macro(span: Span) -> bool {
70     span.ctxt().outer().expn_info().is_some()
71 }
72
73 /// Check if a `DefId`'s path matches the given absolute type path usage.
74 ///
75 /// # Examples
76 /// ```rust,ignore
77 /// match_def_path(cx.tcx, id, &["core", "option", "Option"])
78 /// ```
79 ///
80 /// See also the `paths` module.
81 pub fn match_def_path(tcx: TyCtxt<'_, '_, '_>, def_id: DefId, path: &[&str]) -> bool {
82     use crate::syntax::symbol;
83
84     #[derive(Debug)]
85     struct AbsolutePathBuffer {
86         names: Vec<symbol::LocalInternedString>,
87     }
88
89     impl ty::item_path::ItemPathBuffer for AbsolutePathBuffer {
90         fn root_mode(&self) -> &ty::item_path::RootMode {
91             const ABSOLUTE: &ty::item_path::RootMode = &ty::item_path::RootMode::Absolute;
92             ABSOLUTE
93         }
94
95         fn push(&mut self, text: &str) {
96             self.names.push(symbol::Symbol::intern(text).as_str());
97         }
98     }
99
100     let mut apb = AbsolutePathBuffer { names: vec![] };
101
102     tcx.push_item_path(&mut apb, def_id, false);
103
104     apb.names.len() == path.len()
105         && apb.names
106             .into_iter()
107             .zip(path.iter())
108             .all(|(a, &b)| *a == *b)
109 }
110
111 /// Check if type is struct, enum or union type with given def path.
112 pub fn match_type(cx: &LateContext<'_, '_>, ty: Ty<'_>, path: &[&str]) -> bool {
113     match ty.sty {
114         ty::Adt(adt, _) => match_def_path(cx.tcx, adt.did, path),
115         _ => false,
116     }
117 }
118
119 /// Check if the method call given in `expr` belongs to given trait.
120 pub fn match_trait_method(cx: &LateContext<'_, '_>, expr: &Expr, path: &[&str]) -> bool {
121     let method_call = cx.tables.type_dependent_defs()[expr.hir_id];
122     let trt_id = cx.tcx.trait_of_item(method_call.def_id());
123     if let Some(trt_id) = trt_id {
124         match_def_path(cx.tcx, trt_id, path)
125     } else {
126         false
127     }
128 }
129
130 /// Check if an expression references a variable of the given name.
131 pub fn match_var(expr: &Expr, var: Name) -> bool {
132     if let ExprKind::Path(QPath::Resolved(None, ref path)) = expr.node {
133         if path.segments.len() == 1 && path.segments[0].ident.name == var {
134             return true;
135         }
136     }
137     false
138 }
139
140
141 pub fn last_path_segment(path: &QPath) -> &PathSegment {
142     match *path {
143         QPath::Resolved(_, ref path) => path.segments
144             .last()
145             .expect("A path must have at least one segment"),
146         QPath::TypeRelative(_, ref seg) => seg,
147     }
148 }
149
150 pub fn single_segment_path(path: &QPath) -> Option<&PathSegment> {
151     match *path {
152         QPath::Resolved(_, ref path) if path.segments.len() == 1 => Some(&path.segments[0]),
153         QPath::Resolved(..) => None,
154         QPath::TypeRelative(_, ref seg) => Some(seg),
155     }
156 }
157
158 /// Match a `Path` against a slice of segment string literals.
159 ///
160 /// # Examples
161 /// ```rust,ignore
162 /// match_qpath(path, &["std", "rt", "begin_unwind"])
163 /// ```
164 pub fn match_qpath(path: &QPath, segments: &[&str]) -> bool {
165     match *path {
166         QPath::Resolved(_, ref path) => match_path(path, segments),
167         QPath::TypeRelative(ref ty, ref segment) => match ty.node {
168             TyKind::Path(ref inner_path) => {
169                 !segments.is_empty() && match_qpath(inner_path, &segments[..(segments.len() - 1)])
170                     && segment.ident.name == segments[segments.len() - 1]
171             },
172             _ => false,
173         },
174     }
175 }
176
177 pub fn match_path(path: &Path, segments: &[&str]) -> bool {
178     path.segments
179         .iter()
180         .rev()
181         .zip(segments.iter().rev())
182         .all(|(a, b)| a.ident.name == *b)
183 }
184
185 /// Match a `Path` against a slice of segment string literals, e.g.
186 ///
187 /// # Examples
188 /// ```rust,ignore
189 /// match_qpath(path, &["std", "rt", "begin_unwind"])
190 /// ```
191 pub fn match_path_ast(path: &ast::Path, segments: &[&str]) -> bool {
192     path.segments
193         .iter()
194         .rev()
195         .zip(segments.iter().rev())
196         .all(|(a, b)| a.ident.name == *b)
197 }
198
199 /// Get the definition associated to a path.
200 pub fn path_to_def(cx: &LateContext<'_, '_>, path: &[&str]) -> Option<def::Def> {
201     let crates = cx.tcx.crates();
202     let krate = crates
203         .iter()
204         .find(|&&krate| cx.tcx.crate_name(krate) == path[0]);
205     if let Some(krate) = krate {
206         let krate = DefId {
207             krate: *krate,
208             index: CRATE_DEF_INDEX,
209         };
210         let mut items = cx.tcx.item_children(krate);
211         let mut path_it = path.iter().skip(1).peekable();
212
213         loop {
214             let segment = match path_it.next() {
215                 Some(segment) => segment,
216                 None => return None,
217             };
218
219             for item in mem::replace(&mut items, Rc::new(vec![])).iter() {
220                 if item.ident.name == *segment {
221                     if path_it.peek().is_none() {
222                         return Some(item.def);
223                     }
224
225                     items = cx.tcx.item_children(item.def.def_id());
226                     break;
227                 }
228             }
229         }
230     } else {
231         None
232     }
233 }
234
235 /// Convenience function to get the `DefId` of a trait by path.
236 pub fn get_trait_def_id(cx: &LateContext<'_, '_>, path: &[&str]) -> Option<DefId> {
237     let def = match path_to_def(cx, path) {
238         Some(def) => def,
239         None => return None,
240     };
241
242     match def {
243         def::Def::Trait(trait_id) => Some(trait_id),
244         _ => None,
245     }
246 }
247
248 /// Check whether a type implements a trait.
249 /// See also `get_trait_def_id`.
250 pub fn implements_trait<'a, 'tcx>(
251     cx: &LateContext<'a, 'tcx>,
252     ty: Ty<'tcx>,
253     trait_id: DefId,
254     ty_params: &[Kind<'tcx>],
255 ) -> bool {
256     let ty = cx.tcx.erase_regions(&ty);
257     let obligation =
258         cx.tcx
259             .predicate_for_trait_def(cx.param_env, traits::ObligationCause::dummy(), trait_id, 0, ty, ty_params);
260     cx.tcx.infer_ctxt().enter(|infcx| infcx.predicate_must_hold(&obligation))
261 }
262
263 /// Check whether this type implements Drop.
264 pub fn has_drop(cx: &LateContext<'_, '_>, expr: &Expr) -> bool {
265     let struct_ty = cx.tables.expr_ty(expr);
266     match struct_ty.ty_adt_def() {
267         Some(def) => def.has_dtor(cx.tcx),
268         _ => false,
269     }
270 }
271
272 /// Resolve the definition of a node from its `HirId`.
273 pub fn resolve_node(cx: &LateContext<'_, '_>, qpath: &QPath, id: HirId) -> def::Def {
274     cx.tables.qpath_def(qpath, id)
275 }
276
277 /// Return the method names and argument list of nested method call expressions that make up
278 /// `expr`.
279 pub fn method_calls<'a>(expr: &'a Expr, max_depth: usize) -> (Vec<Symbol>, Vec<&'a [Expr]>) {
280     let mut method_names = Vec::with_capacity(max_depth);
281     let mut arg_lists = Vec::with_capacity(max_depth);
282
283     let mut current = expr;
284     for _ in 0..max_depth {
285         if let ExprKind::MethodCall(path, _, args) = &current.node {
286             if args.iter().any(|e| in_macro(e.span)) {
287                 break;
288             }
289             method_names.push(path.ident.name);
290             arg_lists.push(&**args);
291             current = &args[0];
292         } else {
293             break;
294         }
295     }
296
297     (method_names, arg_lists)
298 }
299
300 /// Match an `Expr` against a chain of methods, and return the matched `Expr`s.
301 ///
302 /// For example, if `expr` represents the `.baz()` in `foo.bar().baz()`,
303 /// `matched_method_chain(expr, &["bar", "baz"])` will return a `Vec`
304 /// containing the `Expr`s for
305 /// `.bar()` and `.baz()`
306 pub fn method_chain_args<'a>(expr: &'a Expr, methods: &[&str]) -> Option<Vec<&'a [Expr]>> {
307     let mut current = expr;
308     let mut matched = Vec::with_capacity(methods.len());
309     for method_name in methods.iter().rev() {
310         // method chains are stored last -> first
311         if let ExprKind::MethodCall(ref path, _, ref args) = current.node {
312             if path.ident.name == *method_name {
313                 if args.iter().any(|e| in_macro(e.span)) {
314                     return None;
315                 }
316                 matched.push(&**args); // build up `matched` backwards
317                 current = &args[0] // go to parent expression
318             } else {
319                 return None;
320             }
321         } else {
322             return None;
323         }
324     }
325     matched.reverse(); // reverse `matched`, so that it is in the same order as `methods`
326     Some(matched)
327 }
328
329
330 /// Get the name of the item the expression is in, if available.
331 pub fn get_item_name(cx: &LateContext<'_, '_>, expr: &Expr) -> Option<Name> {
332     let parent_id = cx.tcx.hir.get_parent(expr.id);
333     match cx.tcx.hir.find(parent_id) {
334         Some(Node::Item(&Item { ref name, .. })) => Some(*name),
335         Some(Node::TraitItem(&TraitItem { ident, .. })) |
336         Some(Node::ImplItem(&ImplItem { ident, .. })) => Some(ident.name),
337         _ => None,
338     }
339 }
340
341 /// Get the name of a `Pat`, if any
342 pub fn get_pat_name(pat: &Pat) -> Option<Name> {
343     match pat.node {
344         PatKind::Binding(_, _, ref spname, _) => Some(spname.name),
345         PatKind::Path(ref qpath) => single_segment_path(qpath).map(|ps| ps.ident.name),
346         PatKind::Box(ref p) | PatKind::Ref(ref p, _) => get_pat_name(&*p),
347         _ => None,
348     }
349 }
350
351 struct ContainsName {
352     name: Name,
353     result: bool,
354 }
355
356 impl<'tcx> Visitor<'tcx> for ContainsName {
357     fn visit_name(&mut self, _: Span, name: Name) {
358         if self.name == name {
359             self.result = true;
360         }
361     }
362     fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'tcx> {
363         NestedVisitorMap::None
364     }
365 }
366
367 /// check if an `Expr` contains a certain name
368 pub fn contains_name(name: Name, expr: &Expr) -> bool {
369     let mut cn = ContainsName {
370         name,
371         result: false,
372     };
373     cn.visit_expr(expr);
374     cn.result
375 }
376
377
378 /// Convert a span to a code snippet if available, otherwise use default.
379 ///
380 /// # Example
381 /// ```rust,ignore
382 /// snippet(cx, expr.span, "..")
383 /// ```
384 pub fn snippet<'a, 'b, T: LintContext<'b>>(cx: &T, span: Span, default: &'a str) -> Cow<'a, str> {
385     snippet_opt(cx, span).map_or_else(|| Cow::Borrowed(default), From::from)
386 }
387
388 /// Same as `snippet`, but should only be used when it's clear that the input span is
389 /// not a macro argument.
390 pub fn snippet_with_macro_callsite<'a, 'b, T: LintContext<'b>>(cx: &T, span: Span, default: &'a str) -> Cow<'a, str> {
391     snippet(cx, span.source_callsite(), default)
392 }
393
394 /// Convert a span to a code snippet. Returns `None` if not available.
395 pub fn snippet_opt<'a, T: LintContext<'a>>(cx: &T, span: Span) -> Option<String> {
396     cx.sess().source_map().span_to_snippet(span).ok()
397 }
398
399 /// Convert a span (from a block) to a code snippet if available, otherwise use
400 /// default.
401 /// This trims the code of indentation, except for the first line. Use it for
402 /// blocks or block-like
403 /// things which need to be printed as such.
404 ///
405 /// # Example
406 /// ```rust,ignore
407 /// snippet(cx, expr.span, "..")
408 /// ```
409 pub fn snippet_block<'a, 'b, T: LintContext<'b>>(cx: &T, span: Span, default: &'a str) -> Cow<'a, str> {
410     let snip = snippet(cx, span, default);
411     trim_multiline(snip, true)
412 }
413
414 /// Returns a new Span that covers the full last line of the given Span
415 pub fn last_line_of_span<'a, T: LintContext<'a>>(cx: &T, span: Span) -> Span {
416     let file_map_and_line = cx.sess().source_map().lookup_line(span.lo()).unwrap();
417     let line_no = file_map_and_line.line;
418     let line_start = &file_map_and_line.sf.lines[line_no];
419     Span::new(*line_start, span.hi(), span.ctxt())
420 }
421
422 /// Like `snippet_block`, but add braces if the expr is not an `ExprKind::Block`.
423 /// Also takes an `Option<String>` which can be put inside the braces.
424 pub fn expr_block<'a, 'b, T: LintContext<'b>>(
425     cx: &T,
426     expr: &Expr,
427     option: Option<String>,
428     default: &'a str,
429 ) -> Cow<'a, str> {
430     let code = snippet_block(cx, expr.span, default);
431     let string = option.unwrap_or_default();
432     if in_macro(expr.span) {
433         Cow::Owned(format!("{{ {} }}", snippet_with_macro_callsite(cx, expr.span, default)))
434     }
435     else if let ExprKind::Block(_, _) = expr.node {
436         Cow::Owned(format!("{}{}", code, string))
437     } else if string.is_empty() {
438         Cow::Owned(format!("{{ {} }}", code))
439     } else {
440         Cow::Owned(format!("{{\n{};\n{}\n}}", code, string))
441     }
442 }
443
444 /// Trim indentation from a multiline string with possibility of ignoring the
445 /// first line.
446 pub fn trim_multiline(s: Cow<'_, str>, ignore_first: bool) -> Cow<'_, str> {
447     let s_space = trim_multiline_inner(s, ignore_first, ' ');
448     let s_tab = trim_multiline_inner(s_space, ignore_first, '\t');
449     trim_multiline_inner(s_tab, ignore_first, ' ')
450 }
451
452 fn trim_multiline_inner(s: Cow<'_, str>, ignore_first: bool, ch: char) -> Cow<'_, str> {
453     let x = s.lines()
454         .skip(ignore_first as usize)
455         .filter_map(|l| {
456             if l.is_empty() {
457                 None
458             } else {
459                 // ignore empty lines
460                 Some(
461                     l.char_indices()
462                         .find(|&(_, x)| x != ch)
463                         .unwrap_or((l.len(), ch))
464                         .0,
465                 )
466             }
467         })
468         .min()
469         .unwrap_or(0);
470     if x > 0 {
471         Cow::Owned(
472             s.lines()
473                 .enumerate()
474                 .map(|(i, l)| {
475                     if (ignore_first && i == 0) || l.is_empty() {
476                         l
477                     } else {
478                         l.split_at(x).1
479                     }
480                 })
481                 .collect::<Vec<_>>()
482                 .join("\n"),
483         )
484     } else {
485         s
486     }
487 }
488
489 /// Get a parent expressions if any â€“ this is useful to constrain a lint.
490 pub fn get_parent_expr<'c>(cx: &'c LateContext<'_, '_>, e: &Expr) -> Option<&'c Expr> {
491     let map = &cx.tcx.hir;
492     let node_id: NodeId = e.id;
493     let parent_id: NodeId = map.get_parent_node(node_id);
494     if node_id == parent_id {
495         return None;
496     }
497     map.find(parent_id).and_then(|node| {
498         if let Node::Expr(parent) = node {
499             Some(parent)
500         } else {
501             None
502         }
503     })
504 }
505
506 pub fn get_enclosing_block<'a, 'tcx: 'a>(cx: &LateContext<'a, 'tcx>, node: NodeId) -> Option<&'tcx Block> {
507     let map = &cx.tcx.hir;
508     let enclosing_node = map.get_enclosing_scope(node)
509         .and_then(|enclosing_id| map.find(enclosing_id));
510     if let Some(node) = enclosing_node {
511         match node {
512             Node::Block(block) => Some(block),
513             Node::Item(&Item {
514                 node: ItemKind::Fn(_, _, _, eid),
515                 ..
516             }) | Node::ImplItem(&ImplItem {
517                 node: ImplItemKind::Method(_, eid),
518                 ..
519             }) => match cx.tcx.hir.body(eid).value.node {
520                 ExprKind::Block(ref block, _) => Some(block),
521                 _ => None,
522             },
523             _ => None,
524         }
525     } else {
526         None
527     }
528 }
529
530 pub struct DiagnosticWrapper<'a>(pub DiagnosticBuilder<'a>);
531
532 impl<'a> Drop for DiagnosticWrapper<'a> {
533     fn drop(&mut self) {
534         self.0.emit();
535     }
536 }
537
538 impl<'a> DiagnosticWrapper<'a> {
539     fn docs_link(&mut self, lint: &'static Lint) {
540         if env::var("CLIPPY_DISABLE_DOCS_LINKS").is_err() {
541             self.0.help(&format!(
542                 "for further information visit https://rust-lang.github.io/rust-clippy/{}/index.html#{}",
543                 &option_env!("RUST_RELEASE_NUM").map_or("master".to_string(), |n| {
544                     // extract just major + minor version and ignore patch versions
545                     format!("rust-{}", n.rsplitn(2, '.').nth(1).unwrap())
546                 }),
547                 lint.name_lower().replacen("clippy::", "", 1)
548             ));
549         }
550     }
551 }
552
553 pub fn span_lint<'a, T: LintContext<'a>>(cx: &T, lint: &'static Lint, sp: Span, msg: &str) {
554     DiagnosticWrapper(cx.struct_span_lint(lint, sp, msg)).docs_link(lint);
555 }
556
557 pub fn span_help_and_lint<'a, 'tcx: 'a, T: LintContext<'tcx>>(
558     cx: &'a T,
559     lint: &'static Lint,
560     span: Span,
561     msg: &str,
562     help: &str,
563 ) {
564     let mut db = DiagnosticWrapper(cx.struct_span_lint(lint, span, msg));
565     db.0.help(help);
566     db.docs_link(lint);
567 }
568
569 pub fn span_note_and_lint<'a, 'tcx: 'a, T: LintContext<'tcx>>(
570     cx: &'a T,
571     lint: &'static Lint,
572     span: Span,
573     msg: &str,
574     note_span: Span,
575     note: &str,
576 ) {
577     let mut db = DiagnosticWrapper(cx.struct_span_lint(lint, span, msg));
578     if note_span == span {
579         db.0.note(note);
580     } else {
581         db.0.span_note(note_span, note);
582     }
583     db.docs_link(lint);
584 }
585
586 pub fn span_lint_and_then<'a, 'tcx: 'a, T: LintContext<'tcx>, F>(
587     cx: &'a T,
588     lint: &'static Lint,
589     sp: Span,
590     msg: &str,
591     f: F,
592 ) where
593     F: for<'b> FnOnce(&mut DiagnosticBuilder<'b>),
594 {
595     let mut db = DiagnosticWrapper(cx.struct_span_lint(lint, sp, msg));
596     f(&mut db.0);
597     db.docs_link(lint);
598 }
599
600 pub fn span_lint_node(cx: &LateContext<'_, '_>, lint: &'static Lint, node: NodeId, sp: Span, msg: &str) {
601     DiagnosticWrapper(cx.tcx.struct_span_lint_node(lint, node, sp, msg)).docs_link(lint);
602 }
603
604 pub fn span_lint_node_and_then(
605     cx: &LateContext<'_, '_>,
606     lint: &'static Lint,
607     node: NodeId,
608     sp: Span,
609     msg: &str,
610     f: impl FnOnce(&mut DiagnosticBuilder<'_>),
611 ) {
612     let mut db = DiagnosticWrapper(cx.tcx.struct_span_lint_node(lint, node, sp, msg));
613     f(&mut db.0);
614     db.docs_link(lint);
615 }
616
617 /// Add a span lint with a suggestion on how to fix it.
618 ///
619 /// These suggestions can be parsed by rustfix to allow it to automatically fix your code.
620 /// In the example below, `help` is `"try"` and `sugg` is the suggested replacement `".any(|x| x > 2)"`.
621 ///
622 /// ```ignore
623 /// error: This `.fold` can be more succinctly expressed as `.any`
624 /// --> $DIR/methods.rs:390:13
625 ///     |
626 /// 390 |     let _ = (0..3).fold(false, |acc, x| acc || x > 2);
627 ///     |                   ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: try: `.any(|x| x > 2)`
628 ///     |
629 ///     = note: `-D fold-any` implied by `-D warnings`
630 /// ```
631 pub fn span_lint_and_sugg<'a, 'tcx: 'a, T: LintContext<'tcx>>(
632     cx: &'a T,
633     lint: &'static Lint,
634     sp: Span,
635     msg: &str,
636     help: &str,
637     sugg: String,
638 ) {
639     span_lint_and_then(cx, lint, sp, msg, |db| {
640         db.span_suggestion_with_applicability(sp, help, sugg, Applicability::Unspecified);
641     });
642 }
643
644 /// Create a suggestion made from several `span â†’ replacement`.
645 ///
646 /// Note: in the JSON format (used by `compiletest_rs`), the help message will
647 /// appear once per
648 /// replacement. In human-readable format though, it only appears once before
649 /// the whole suggestion.
650 pub fn multispan_sugg<I>(db: &mut DiagnosticBuilder<'_>, help_msg: String, sugg: I)
651 where
652     I: IntoIterator<Item = (Span, String)>,
653 {
654     let sugg = CodeSuggestion {
655         substitutions: vec![
656             Substitution {
657                 parts: sugg.into_iter()
658                     .map(|(span, snippet)| {
659                         SubstitutionPart {
660                             snippet,
661                             span,
662                         }
663                     })
664                     .collect(),
665             }
666         ],
667         msg: help_msg,
668         show_code_when_inline: true,
669         applicability: Applicability::Unspecified,
670     };
671     db.suggestions.push(sugg);
672 }
673
674 /// Return the base type for HIR references and pointers.
675 pub fn walk_ptrs_hir_ty(ty: &hir::Ty) -> &hir::Ty {
676     match ty.node {
677         TyKind::Ptr(ref mut_ty) | TyKind::Rptr(_, ref mut_ty) => walk_ptrs_hir_ty(&mut_ty.ty),
678         _ => ty,
679     }
680 }
681
682 /// Return the base type for references and raw pointers.
683 pub fn walk_ptrs_ty(ty: Ty<'_>) -> Ty<'_> {
684     match ty.sty {
685         ty::Ref(_, ty, _) => walk_ptrs_ty(ty),
686         _ => ty,
687     }
688 }
689
690 /// Return the base type for references and raw pointers, and count reference
691 /// depth.
692 pub fn walk_ptrs_ty_depth(ty: Ty<'_>) -> (Ty<'_>, usize) {
693     fn inner(ty: Ty<'_>, depth: usize) -> (Ty<'_>, usize) {
694         match ty.sty {
695             ty::Ref(_, ty, _) => inner(ty, depth + 1),
696             _ => (ty, depth),
697         }
698     }
699     inner(ty, 0)
700 }
701
702 /// Check whether the given expression is a constant literal of the given value.
703 pub fn is_integer_literal(expr: &Expr, value: u128) -> bool {
704     // FIXME: use constant folding
705     if let ExprKind::Lit(ref spanned) = expr.node {
706         if let LitKind::Int(v, _) = spanned.node {
707             return v == value;
708         }
709     }
710     false
711 }
712
713 pub fn is_adjusted(cx: &LateContext<'_, '_>, e: &Expr) -> bool {
714     cx.tables.adjustments().get(e.hir_id).is_some()
715 }
716
717 pub struct LimitStack {
718     stack: Vec<u64>,
719 }
720
721 impl Drop for LimitStack {
722     fn drop(&mut self) {
723         assert_eq!(self.stack.len(), 1);
724     }
725 }
726
727 impl LimitStack {
728     pub fn new(limit: u64) -> Self {
729         Self { stack: vec![limit] }
730     }
731     pub fn limit(&self) -> u64 {
732         *self.stack
733             .last()
734             .expect("there should always be a value in the stack")
735     }
736     pub fn push_attrs(&mut self, sess: &Session, attrs: &[ast::Attribute], name: &'static str) {
737         let stack = &mut self.stack;
738         parse_attrs(sess, attrs, name, |val| stack.push(val));
739     }
740     pub fn pop_attrs(&mut self, sess: &Session, attrs: &[ast::Attribute], name: &'static str) {
741         let stack = &mut self.stack;
742         parse_attrs(sess, attrs, name, |val| assert_eq!(stack.pop(), Some(val)));
743     }
744 }
745
746 pub fn get_attr<'a>(attrs: &'a [ast::Attribute], name: &'static str) -> impl Iterator<Item = &'a ast::Attribute> {
747     attrs.iter().filter(move |attr|
748         attr.path.segments.len() == 2 &&
749         attr.path.segments[0].ident.to_string() == "clippy" &&
750         attr.path.segments[1].ident.to_string() == name)
751 }
752
753 fn parse_attrs<F: FnMut(u64)>(sess: &Session, attrs: &[ast::Attribute], name: &'static str, mut f: F) {
754     for attr in get_attr(attrs, name) {
755         if let Some(ref value) = attr.value_str() {
756             if let Ok(value) = FromStr::from_str(&value.as_str()) {
757                 f(value)
758             } else {
759                 sess.span_err(attr.span, "not a number");
760             }
761         } else {
762             sess.span_err(attr.span, "bad clippy attribute");
763         }
764     }
765 }
766
767 /// Return the pre-expansion span if is this comes from an expansion of the
768 /// macro `name`.
769 /// See also `is_direct_expn_of`.
770 pub fn is_expn_of(mut span: Span, name: &str) -> Option<Span> {
771     loop {
772         let span_name_span = span.ctxt()
773             .outer()
774             .expn_info()
775             .map(|ei| (ei.format.name(), ei.call_site));
776
777         match span_name_span {
778             Some((mac_name, new_span)) if mac_name == name => return Some(new_span),
779             None => return None,
780             Some((_, new_span)) => span = new_span,
781         }
782     }
783 }
784
785 /// Return the pre-expansion span if is this directly comes from an expansion
786 /// of the macro `name`.
787 /// The difference with `is_expn_of` is that in
788 /// ```rust,ignore
789 /// foo!(bar!(42));
790 /// ```
791 /// `42` is considered expanded from `foo!` and `bar!` by `is_expn_of` but only
792 /// `bar!` by
793 /// `is_direct_expn_of`.
794 pub fn is_direct_expn_of(span: Span, name: &str) -> Option<Span> {
795     let span_name_span = span.ctxt()
796         .outer()
797         .expn_info()
798         .map(|ei| (ei.format.name(), ei.call_site));
799
800     match span_name_span {
801         Some((mac_name, new_span)) if mac_name == name => Some(new_span),
802         _ => None,
803     }
804 }
805
806 /// Convenience function to get the return type of a function
807 pub fn return_ty<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, fn_item: NodeId) -> Ty<'tcx> {
808     let fn_def_id = cx.tcx.hir.local_def_id(fn_item);
809     let ret_ty = cx.tcx.fn_sig(fn_def_id).output();
810     cx.tcx.erase_late_bound_regions(&ret_ty)
811 }
812
813 /// Check if two types are the same.
814 ///
815 /// This discards any lifetime annotations, too.
816 // FIXME: this works correctly for lifetimes bounds (`for <'a> Foo<'a>` == `for
817 // <'b> Foo<'b>` but
818 // not for type parameters.
819 pub fn same_tys<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, a: Ty<'tcx>, b: Ty<'tcx>) -> bool {
820     let a = cx.tcx.erase_late_bound_regions(&Binder::bind(a));
821     let b = cx.tcx.erase_late_bound_regions(&Binder::bind(b));
822     cx.tcx
823         .infer_ctxt()
824         .enter(|infcx| infcx.can_eq(cx.param_env, a, b).is_ok())
825 }
826
827 /// Return whether the given type is an `unsafe` function.
828 pub fn type_is_unsafe_function<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, ty: Ty<'tcx>) -> bool {
829     match ty.sty {
830         ty::FnDef(..) | ty::FnPtr(_) => ty.fn_sig(cx.tcx).unsafety() == Unsafety::Unsafe,
831         _ => false,
832     }
833 }
834
835 pub fn is_copy<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, ty: Ty<'tcx>) -> bool {
836     !ty.moves_by_default(cx.tcx.global_tcx(), cx.param_env, DUMMY_SP)
837 }
838
839 /// Return whether a pattern is refutable.
840 pub fn is_refutable(cx: &LateContext<'_, '_>, pat: &Pat) -> bool {
841     fn is_enum_variant(cx: &LateContext<'_, '_>, qpath: &QPath, id: HirId) -> bool {
842         matches!(
843             cx.tables.qpath_def(qpath, id),
844             def::Def::Variant(..) | def::Def::VariantCtor(..)
845         )
846     }
847
848     fn are_refutable<'a, I: Iterator<Item = &'a Pat>>(cx: &LateContext<'_, '_>, mut i: I) -> bool {
849         i.any(|pat| is_refutable(cx, pat))
850     }
851
852     match pat.node {
853         PatKind::Binding(..) | PatKind::Wild => false,
854         PatKind::Box(ref pat) | PatKind::Ref(ref pat, _) => is_refutable(cx, pat),
855         PatKind::Lit(..) | PatKind::Range(..) => true,
856         PatKind::Path(ref qpath) => is_enum_variant(cx, qpath, pat.hir_id),
857         PatKind::Tuple(ref pats, _) => are_refutable(cx, pats.iter().map(|pat| &**pat)),
858         PatKind::Struct(ref qpath, ref fields, _) => if is_enum_variant(cx, qpath, pat.hir_id) {
859             true
860         } else {
861             are_refutable(cx, fields.iter().map(|field| &*field.node.pat))
862         },
863         PatKind::TupleStruct(ref qpath, ref pats, _) => if is_enum_variant(cx, qpath, pat.hir_id) {
864             true
865         } else {
866             are_refutable(cx, pats.iter().map(|pat| &**pat))
867         },
868         PatKind::Slice(ref head, ref middle, ref tail) => are_refutable(
869             cx,
870             head.iter()
871                 .chain(middle)
872                 .chain(tail.iter())
873                 .map(|pat| &**pat),
874         ),
875     }
876 }
877
878 /// Checks for the `#[automatically_derived]` attribute all `#[derive]`d
879 /// implementations have.
880 pub fn is_automatically_derived(attrs: &[ast::Attribute]) -> bool {
881     attr::contains_name(attrs, "automatically_derived")
882 }
883
884 /// Remove blocks around an expression.
885 ///
886 /// Ie. `x`, `{ x }` and `{{{{ x }}}}` all give `x`. `{ x; y }` and `{}` return
887 /// themselves.
888 pub fn remove_blocks(expr: &Expr) -> &Expr {
889     if let ExprKind::Block(ref block, _) = expr.node {
890         if block.stmts.is_empty() {
891             if let Some(ref expr) = block.expr {
892                 remove_blocks(expr)
893             } else {
894                 expr
895             }
896         } else {
897             expr
898         }
899     } else {
900         expr
901     }
902 }
903
904 pub fn opt_def_id(def: Def) -> Option<DefId> {
905     match def {
906         Def::Fn(id) |
907         Def::Mod(id) |
908         Def::Static(id, _) |
909         Def::Variant(id) |
910         Def::VariantCtor(id, ..) |
911         Def::Enum(id) |
912         Def::TyAlias(id) |
913         Def::AssociatedTy(id) |
914         Def::TyParam(id) |
915         Def::ForeignTy(id) |
916         Def::Struct(id) |
917         Def::StructCtor(id, ..) |
918         Def::Union(id) |
919         Def::Trait(id) |
920         Def::TraitAlias(id) |
921         Def::Method(id) |
922         Def::Const(id) |
923         Def::AssociatedConst(id) |
924         Def::Macro(id, ..) |
925         Def::Existential(id) |
926         Def::AssociatedExistential(id) |
927         Def::SelfCtor(id)
928         => Some(id),
929
930         Def::Upvar(..) | Def::Local(_) | Def::Label(..) | Def::PrimTy(..) | Def::SelfTy(..) |
931         Def::ToolMod | Def::NonMacroAttr{..} | Def::Err => None,
932     }
933 }
934
935 pub fn is_self(slf: &Arg) -> bool {
936     if let PatKind::Binding(_, _, name, _) = slf.pat.node {
937         name.name == keywords::SelfValue.name()
938     } else {
939         false
940     }
941 }
942
943 pub fn is_self_ty(slf: &hir::Ty) -> bool {
944     if_chain! {
945         if let TyKind::Path(ref qp) = slf.node;
946         if let QPath::Resolved(None, ref path) = *qp;
947         if let Def::SelfTy(..) = path.def;
948         then {
949             return true
950         }
951     }
952     false
953 }
954
955 pub fn iter_input_pats<'tcx>(decl: &FnDecl, body: &'tcx Body) -> impl Iterator<Item = &'tcx Arg> {
956     (0..decl.inputs.len()).map(move |i| &body.arguments[i])
957 }
958
959 /// Check if a given expression is a match expression
960 /// expanded from `?` operator or `try` macro.
961 pub fn is_try(expr: &Expr) -> Option<&Expr> {
962     fn is_ok(arm: &Arm) -> bool {
963         if_chain! {
964             if let PatKind::TupleStruct(ref path, ref pat, None) = arm.pats[0].node;
965             if match_qpath(path, &paths::RESULT_OK[1..]);
966             if let PatKind::Binding(_, defid, _, None) = pat[0].node;
967             if let ExprKind::Path(QPath::Resolved(None, ref path)) = arm.body.node;
968             if let Def::Local(lid) = path.def;
969             if lid == defid;
970             then {
971                 return true;
972             }
973         }
974         false
975     }
976
977     fn is_err(arm: &Arm) -> bool {
978         if let PatKind::TupleStruct(ref path, _, _) = arm.pats[0].node {
979             match_qpath(path, &paths::RESULT_ERR[1..])
980         } else {
981             false
982         }
983     }
984
985     if let ExprKind::Match(_, ref arms, ref source) = expr.node {
986         // desugared from a `?` operator
987         if let MatchSource::TryDesugar = *source {
988             return Some(expr);
989         }
990
991         if_chain! {
992             if arms.len() == 2;
993             if arms[0].pats.len() == 1 && arms[0].guard.is_none();
994             if arms[1].pats.len() == 1 && arms[1].guard.is_none();
995             if (is_ok(&arms[0]) && is_err(&arms[1])) ||
996                 (is_ok(&arms[1]) && is_err(&arms[0]));
997             then {
998                 return Some(expr);
999             }
1000         }
1001     }
1002
1003     None
1004 }
1005
1006 /// Returns true if the lint is allowed in the current context
1007 ///
1008 /// Useful for skipping long running code when it's unnecessary
1009 pub fn is_allowed(cx: &LateContext<'_, '_>, lint: &'static Lint, id: NodeId) -> bool {
1010     cx.tcx.lint_level_at_node(lint, id).0 == Level::Allow
1011 }
1012
1013 pub fn get_arg_name(pat: &Pat) -> Option<ast::Name> {
1014     match pat.node {
1015         PatKind::Binding(_, _, ident, None) => Some(ident.name),
1016         PatKind::Ref(ref subpat, _) => get_arg_name(subpat),
1017         _ => None,
1018     }
1019 }
1020
1021 pub fn int_bits(tcx: TyCtxt<'_, '_, '_>, ity: ast::IntTy) -> u64 {
1022     layout::Integer::from_attr(&tcx, attr::IntType::SignedInt(ity)).size().bits()
1023 }
1024
1025 #[allow(clippy::cast_possible_wrap)]
1026 /// Turn a constant int byte representation into an i128
1027 pub fn sext(tcx: TyCtxt<'_, '_, '_>, u: u128, ity: ast::IntTy) -> i128 {
1028     let amt = 128 - int_bits(tcx, ity);
1029     ((u as i128) << amt) >> amt
1030 }
1031
1032 #[allow(clippy::cast_sign_loss)]
1033 /// clip unused bytes
1034 pub fn unsext(tcx: TyCtxt<'_, '_, '_>, u: i128, ity: ast::IntTy) -> u128 {
1035     let amt = 128 - int_bits(tcx, ity);
1036     ((u as u128) << amt) >> amt
1037 }
1038
1039 /// clip unused bytes
1040 pub fn clip(tcx: TyCtxt<'_, '_, '_>, u: u128, ity: ast::UintTy) -> u128 {
1041     let bits = layout::Integer::from_attr(&tcx, attr::IntType::UnsignedInt(ity)).size().bits();
1042     let amt = 128 - bits;
1043     (u << amt) >> amt
1044 }
1045
1046 /// Remove block comments from the given Vec of lines
1047 ///
1048 /// # Examples
1049 ///
1050 /// ```rust,ignore
1051 /// without_block_comments(vec!["/*", "foo", "*/"]);
1052 /// // => vec![]
1053 ///
1054 /// without_block_comments(vec!["bar", "/*", "foo", "*/"]);
1055 /// // => vec!["bar"]
1056 /// ```
1057 pub fn without_block_comments(lines: Vec<&str>) -> Vec<&str> {
1058     let mut without = vec![];
1059
1060     let mut nest_level = 0;
1061
1062     for line in lines {
1063         if line.contains("/*") {
1064             nest_level += 1;
1065             continue;
1066         } else if line.contains("*/") {
1067             nest_level -= 1;
1068             continue;
1069         }
1070
1071         if nest_level == 0 {
1072             without.push(line);
1073         }
1074     }
1075
1076     without
1077 }
1078
1079 pub fn any_parent_is_automatically_derived(tcx: TyCtxt<'_, '_, '_>, node: NodeId) -> bool {
1080     let map = &tcx.hir;
1081     let mut prev_enclosing_node = None;
1082     let mut enclosing_node = node;
1083     while Some(enclosing_node) != prev_enclosing_node {
1084         if is_automatically_derived(map.attrs(enclosing_node)) {
1085             return true;
1086         }
1087         prev_enclosing_node = Some(enclosing_node);
1088         enclosing_node = map.get_parent(enclosing_node);
1089     }
1090     false
1091 }
1092
1093 #[cfg(test)]
1094 mod test {
1095     use super::{trim_multiline, without_block_comments};
1096
1097     #[test]
1098     fn test_trim_multiline_single_line() {
1099         assert_eq!("", trim_multiline("".into(), false));
1100         assert_eq!("...", trim_multiline("...".into(), false));
1101         assert_eq!("...", trim_multiline("    ...".into(), false));
1102         assert_eq!("...", trim_multiline("\t...".into(), false));
1103         assert_eq!("...", trim_multiline("\t\t...".into(), false));
1104     }
1105
1106     #[test]
1107     #[rustfmt::skip]
1108     fn test_trim_multiline_block() {
1109         assert_eq!("\
1110     if x {
1111         y
1112     } else {
1113         z
1114     }", trim_multiline("    if x {
1115             y
1116         } else {
1117             z
1118         }".into(), false));
1119         assert_eq!("\
1120     if x {
1121     \ty
1122     } else {
1123     \tz
1124     }", trim_multiline("    if x {
1125         \ty
1126         } else {
1127         \tz
1128         }".into(), false));
1129     }
1130
1131     #[test]
1132     #[rustfmt::skip]
1133     fn test_trim_multiline_empty_line() {
1134         assert_eq!("\
1135     if x {
1136         y
1137
1138     } else {
1139         z
1140     }", trim_multiline("    if x {
1141             y
1142
1143         } else {
1144             z
1145         }".into(), false));
1146     }
1147
1148     #[test]
1149     fn test_without_block_comments_lines_without_block_comments() {
1150         let result = without_block_comments(vec!["/*", "", "*/"]);
1151         println!("result: {:?}", result);
1152         assert!(result.is_empty());
1153
1154         let result = without_block_comments(vec!["", "/*", "", "*/", "#[crate_type = \"lib\"]", "/*", "", "*/", ""]);
1155         assert_eq!(result, vec!["", "#[crate_type = \"lib\"]", ""]);
1156
1157         let result = without_block_comments(vec!["/* rust", "", "*/"]);
1158         assert!(result.is_empty());
1159
1160         let result = without_block_comments(vec!["/* one-line comment */"]);
1161         assert!(result.is_empty());
1162
1163         let result = without_block_comments(vec!["/* nested", "/* multi-line", "comment", "*/", "test", "*/"]);
1164         assert!(result.is_empty());
1165
1166         let result = without_block_comments(vec!["/* nested /* inline /* comment */ test */ */"]);
1167         assert!(result.is_empty());
1168
1169         let result = without_block_comments(vec!["foo", "bar", "baz"]);
1170         assert_eq!(result, vec!["foo", "bar", "baz"]);
1171     }
1172 }