]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/utils/mod.rs
dogfood
[rust.git] / clippy_lints / src / utils / mod.rs
1 #[macro_use]
2 pub mod sym;
3
4 pub mod attrs;
5 pub mod author;
6 pub mod camel_case;
7 pub mod comparisons;
8 pub mod conf;
9 pub mod constants;
10 mod diagnostics;
11 pub mod higher;
12 mod hir_utils;
13 pub mod inspector;
14 pub mod internal_lints;
15 pub mod paths;
16 pub mod ptr;
17 pub mod sugg;
18 pub mod usage;
19 pub use self::attrs::*;
20 pub use self::diagnostics::*;
21 pub use self::hir_utils::{SpanlessEq, SpanlessHash};
22
23 use std::borrow::Cow;
24 use std::mem;
25
26 use if_chain::if_chain;
27 use matches::matches;
28 use rustc::hir;
29 use rustc::hir::def::{DefKind, Res};
30 use rustc::hir::def_id::{DefId, CRATE_DEF_INDEX, LOCAL_CRATE};
31 use rustc::hir::intravisit::{NestedVisitorMap, Visitor};
32 use rustc::hir::Node;
33 use rustc::hir::*;
34 use rustc::lint::{LateContext, Level, Lint, LintContext};
35 use rustc::traits;
36 use rustc::ty::{
37     self,
38     layout::{self, IntegerExt},
39     subst::GenericArg,
40     Binder, Ty, TyCtxt,
41 };
42 use rustc_errors::Applicability;
43 use smallvec::SmallVec;
44 use syntax::ast::{self, LitKind};
45 use syntax::attr;
46 use syntax::source_map::{Span, DUMMY_SP};
47 use syntax::symbol::{kw, Symbol};
48 use syntax_pos::hygiene::ExpnKind;
49
50 use crate::consts::{constant, Constant};
51 use crate::reexport::*;
52
53 /// Returns `true` if the two spans come from differing expansions (i.e., one is
54 /// from a macro and one isn't).
55 #[must_use]
56 pub fn differing_macro_contexts(lhs: Span, rhs: Span) -> bool {
57     rhs.ctxt() != lhs.ctxt()
58 }
59
60 /// Returns `true` if the given `NodeId` is inside a constant context
61 ///
62 /// # Example
63 ///
64 /// ```rust,ignore
65 /// if in_constant(cx, expr.hir_id) {
66 ///     // Do something
67 /// }
68 /// ```
69 pub fn in_constant(cx: &LateContext<'_, '_>, id: HirId) -> bool {
70     let parent_id = cx.tcx.hir().get_parent_item(id);
71     match cx.tcx.hir().get(parent_id) {
72         Node::Item(&Item {
73             kind: ItemKind::Const(..),
74             ..
75         })
76         | Node::TraitItem(&TraitItem {
77             kind: TraitItemKind::Const(..),
78             ..
79         })
80         | Node::ImplItem(&ImplItem {
81             kind: ImplItemKind::Const(..),
82             ..
83         })
84         | Node::AnonConst(_)
85         | Node::Item(&Item {
86             kind: ItemKind::Static(..),
87             ..
88         }) => true,
89         Node::Item(&Item {
90             kind: ItemKind::Fn(ref sig, ..),
91             ..
92         })
93         | Node::ImplItem(&ImplItem {
94             kind: ImplItemKind::Method(ref sig, _),
95             ..
96         }) => sig.header.constness == Constness::Const,
97         _ => false,
98     }
99 }
100
101 /// Returns `true` if this `span` was expanded by any macro.
102 #[must_use]
103 pub fn in_macro(span: Span) -> bool {
104     if span.from_expansion() {
105         if let ExpnKind::Desugaring(..) = span.ctxt().outer_expn_data().kind {
106             false
107         } else {
108             true
109         }
110     } else {
111         false
112     }
113 }
114 // If the snippet is empty, it's an attribute that was inserted during macro
115 // expansion and we want to ignore those, because they could come from external
116 // sources that the user has no control over.
117 // For some reason these attributes don't have any expansion info on them, so
118 // we have to check it this way until there is a better way.
119 pub fn is_present_in_source<T: LintContext>(cx: &T, span: Span) -> bool {
120     if let Some(snippet) = snippet_opt(cx, span) {
121         if snippet.is_empty() {
122             return false;
123         }
124     }
125     true
126 }
127
128 /// Checks if type is struct, enum or union type with the given def path.
129 pub fn match_type(cx: &LateContext<'_, '_>, ty: Ty<'_>, path: &[&str]) -> bool {
130     match ty.kind {
131         ty::Adt(adt, _) => match_def_path(cx, adt.did, path),
132         _ => false,
133     }
134 }
135
136 /// Checks if the type is equal to a diagnostic item
137 pub fn is_type_diagnostic_item(cx: &LateContext<'_, '_>, ty: Ty<'_>, diag_item: Symbol) -> bool {
138     match ty.kind {
139         ty::Adt(adt, _) => cx.tcx.is_diagnostic_item(diag_item, adt.did),
140         _ => false,
141     }
142 }
143
144 /// Checks if the method call given in `expr` belongs to the given trait.
145 pub fn match_trait_method(cx: &LateContext<'_, '_>, expr: &Expr, path: &[&str]) -> bool {
146     let def_id = cx.tables.type_dependent_def_id(expr.hir_id).unwrap();
147     let trt_id = cx.tcx.trait_of_item(def_id);
148     if let Some(trt_id) = trt_id {
149         match_def_path(cx, trt_id, path)
150     } else {
151         false
152     }
153 }
154
155 /// Checks if an expression references a variable of the given name.
156 pub fn match_var(expr: &Expr, var: Name) -> bool {
157     if let ExprKind::Path(QPath::Resolved(None, ref path)) = expr.kind {
158         if path.segments.len() == 1 && path.segments[0].ident.name == var {
159             return true;
160         }
161     }
162     false
163 }
164
165 pub fn last_path_segment(path: &QPath) -> &PathSegment {
166     match *path {
167         QPath::Resolved(_, ref path) => path.segments.last().expect("A path must have at least one segment"),
168         QPath::TypeRelative(_, ref seg) => seg,
169     }
170 }
171
172 pub fn single_segment_path(path: &QPath) -> Option<&PathSegment> {
173     match *path {
174         QPath::Resolved(_, ref path) if path.segments.len() == 1 => Some(&path.segments[0]),
175         QPath::Resolved(..) => None,
176         QPath::TypeRelative(_, ref seg) => Some(seg),
177     }
178 }
179
180 /// Matches a `QPath` against a slice of segment string literals.
181 ///
182 /// There is also `match_path` if you are dealing with a `rustc::hir::Path` instead of a
183 /// `rustc::hir::QPath`.
184 ///
185 /// # Examples
186 /// ```rust,ignore
187 /// match_qpath(path, &["std", "rt", "begin_unwind"])
188 /// ```
189 pub fn match_qpath(path: &QPath, segments: &[&str]) -> bool {
190     match *path {
191         QPath::Resolved(_, ref path) => match_path(path, segments),
192         QPath::TypeRelative(ref ty, ref segment) => match ty.kind {
193             TyKind::Path(ref inner_path) => {
194                 !segments.is_empty()
195                     && match_qpath(inner_path, &segments[..(segments.len() - 1)])
196                     && segment.ident.name.as_str() == segments[segments.len() - 1]
197             },
198             _ => false,
199         },
200     }
201 }
202
203 /// Matches a `Path` against a slice of segment string literals.
204 ///
205 /// There is also `match_qpath` if you are dealing with a `rustc::hir::QPath` instead of a
206 /// `rustc::hir::Path`.
207 ///
208 /// # Examples
209 ///
210 /// ```rust,ignore
211 /// if match_path(&trait_ref.path, &paths::HASH) {
212 ///     // This is the `std::hash::Hash` trait.
213 /// }
214 ///
215 /// if match_path(ty_path, &["rustc", "lint", "Lint"]) {
216 ///     // This is a `rustc::lint::Lint`.
217 /// }
218 /// ```
219 pub fn match_path(path: &Path, segments: &[&str]) -> bool {
220     path.segments
221         .iter()
222         .rev()
223         .zip(segments.iter().rev())
224         .all(|(a, b)| a.ident.name.as_str() == *b)
225 }
226
227 /// Matches a `Path` against a slice of segment string literals, e.g.
228 ///
229 /// # Examples
230 /// ```rust,ignore
231 /// match_qpath(path, &["std", "rt", "begin_unwind"])
232 /// ```
233 pub fn match_path_ast(path: &ast::Path, segments: &[&str]) -> bool {
234     path.segments
235         .iter()
236         .rev()
237         .zip(segments.iter().rev())
238         .all(|(a, b)| a.ident.name.as_str() == *b)
239 }
240
241 /// Gets the definition associated to a path.
242 pub fn path_to_res(cx: &LateContext<'_, '_>, path: &[&str]) -> Option<def::Res> {
243     let crates = cx.tcx.crates();
244     let krate = crates
245         .iter()
246         .find(|&&krate| cx.tcx.crate_name(krate).as_str() == path[0]);
247     if let Some(krate) = krate {
248         let krate = DefId {
249             krate: *krate,
250             index: CRATE_DEF_INDEX,
251         };
252         let mut items = cx.tcx.item_children(krate);
253         let mut path_it = path.iter().skip(1).peekable();
254
255         loop {
256             let segment = match path_it.next() {
257                 Some(segment) => segment,
258                 None => return None,
259             };
260
261             let result = SmallVec::<[_; 8]>::new();
262             for item in mem::replace(&mut items, cx.tcx.arena.alloc_slice(&result)).iter() {
263                 if item.ident.name.as_str() == *segment {
264                     if path_it.peek().is_none() {
265                         return Some(item.res);
266                     }
267
268                     items = cx.tcx.item_children(item.res.def_id());
269                     break;
270                 }
271             }
272         }
273     } else {
274         None
275     }
276 }
277
278 pub fn qpath_res(cx: &LateContext<'_, '_>, qpath: &hir::QPath, id: hir::HirId) -> Res {
279     match qpath {
280         hir::QPath::Resolved(_, path) => path.res,
281         hir::QPath::TypeRelative(..) => {
282             if cx.tcx.has_typeck_tables(id.owner_def_id()) {
283                 cx.tcx.typeck_tables_of(id.owner_def_id()).qpath_res(qpath, id)
284             } else {
285                 Res::Err
286             }
287         },
288     }
289 }
290
291 /// Convenience function to get the `DefId` of a trait by path.
292 /// It could be a trait or trait alias.
293 pub fn get_trait_def_id(cx: &LateContext<'_, '_>, path: &[&str]) -> Option<DefId> {
294     let res = match path_to_res(cx, path) {
295         Some(res) => res,
296         None => return None,
297     };
298
299     match res {
300         Res::Def(DefKind::Trait, trait_id) | Res::Def(DefKind::TraitAlias, trait_id) => Some(trait_id),
301         Res::Err => unreachable!("this trait resolution is impossible: {:?}", &path),
302         _ => None,
303     }
304 }
305
306 /// Checks whether a type implements a trait.
307 /// See also `get_trait_def_id`.
308 pub fn implements_trait<'a, 'tcx>(
309     cx: &LateContext<'a, 'tcx>,
310     ty: Ty<'tcx>,
311     trait_id: DefId,
312     ty_params: &[GenericArg<'tcx>],
313 ) -> bool {
314     let ty = cx.tcx.erase_regions(&ty);
315     let obligation = cx.tcx.predicate_for_trait_def(
316         cx.param_env,
317         traits::ObligationCause::dummy(),
318         trait_id,
319         0,
320         ty,
321         ty_params,
322     );
323     cx.tcx
324         .infer_ctxt()
325         .enter(|infcx| infcx.predicate_must_hold_modulo_regions(&obligation))
326 }
327
328 /// Gets the `hir::TraitRef` of the trait the given method is implemented for.
329 ///
330 /// Use this if you want to find the `TraitRef` of the `Add` trait in this example:
331 ///
332 /// ```rust
333 /// struct Point(isize, isize);
334 ///
335 /// impl std::ops::Add for Point {
336 ///     type Output = Self;
337 ///
338 ///     fn add(self, other: Self) -> Self {
339 ///         Point(0, 0)
340 ///     }
341 /// }
342 /// ```
343 pub fn trait_ref_of_method<'tcx>(cx: &LateContext<'_, 'tcx>, hir_id: HirId) -> Option<&'tcx TraitRef> {
344     // Get the implemented trait for the current function
345     let parent_impl = cx.tcx.hir().get_parent_item(hir_id);
346     if_chain! {
347         if parent_impl != hir::CRATE_HIR_ID;
348         if let hir::Node::Item(item) = cx.tcx.hir().get(parent_impl);
349         if let hir::ItemKind::Impl(_, _, _, _, trait_ref, _, _) = &item.kind;
350         then { return trait_ref.as_ref(); }
351     }
352     None
353 }
354
355 /// Checks whether this type implements `Drop`.
356 pub fn has_drop<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, ty: Ty<'tcx>) -> bool {
357     match ty.ty_adt_def() {
358         Some(def) => def.has_dtor(cx.tcx),
359         _ => false,
360     }
361 }
362
363 /// Returns the method names and argument list of nested method call expressions that make up
364 /// `expr`. method/span lists are sorted with the most recent call first.
365 pub fn method_calls(expr: &Expr, max_depth: usize) -> (Vec<Symbol>, Vec<&[Expr]>, Vec<Span>) {
366     let mut method_names = Vec::with_capacity(max_depth);
367     let mut arg_lists = Vec::with_capacity(max_depth);
368     let mut spans = Vec::with_capacity(max_depth);
369
370     let mut current = expr;
371     for _ in 0..max_depth {
372         if let ExprKind::MethodCall(path, span, args) = &current.kind {
373             if args.iter().any(|e| e.span.from_expansion()) {
374                 break;
375             }
376             method_names.push(path.ident.name);
377             arg_lists.push(&**args);
378             spans.push(*span);
379             current = &args[0];
380         } else {
381             break;
382         }
383     }
384
385     (method_names, arg_lists, spans)
386 }
387
388 /// Matches an `Expr` against a chain of methods, and return the matched `Expr`s.
389 ///
390 /// For example, if `expr` represents the `.baz()` in `foo.bar().baz()`,
391 /// `matched_method_chain(expr, &["bar", "baz"])` will return a `Vec`
392 /// containing the `Expr`s for
393 /// `.bar()` and `.baz()`
394 pub fn method_chain_args<'a>(expr: &'a Expr, methods: &[&str]) -> Option<Vec<&'a [Expr]>> {
395     let mut current = expr;
396     let mut matched = Vec::with_capacity(methods.len());
397     for method_name in methods.iter().rev() {
398         // method chains are stored last -> first
399         if let ExprKind::MethodCall(ref path, _, ref args) = current.kind {
400             if path.ident.name.as_str() == *method_name {
401                 if args.iter().any(|e| e.span.from_expansion()) {
402                     return None;
403                 }
404                 matched.push(&**args); // build up `matched` backwards
405                 current = &args[0] // go to parent expression
406             } else {
407                 return None;
408             }
409         } else {
410             return None;
411         }
412     }
413     // Reverse `matched` so that it is in the same order as `methods`.
414     matched.reverse();
415     Some(matched)
416 }
417
418 /// Returns `true` if the provided `def_id` is an entrypoint to a program.
419 pub fn is_entrypoint_fn(cx: &LateContext<'_, '_>, def_id: DefId) -> bool {
420     cx.tcx
421         .entry_fn(LOCAL_CRATE)
422         .map_or(false, |(entry_fn_def_id, _)| def_id == entry_fn_def_id)
423 }
424
425 /// Gets the name of the item the expression is in, if available.
426 pub fn get_item_name(cx: &LateContext<'_, '_>, expr: &Expr) -> Option<Name> {
427     let parent_id = cx.tcx.hir().get_parent_item(expr.hir_id);
428     match cx.tcx.hir().find(parent_id) {
429         Some(Node::Item(&Item { ref ident, .. })) => Some(ident.name),
430         Some(Node::TraitItem(&TraitItem { ident, .. })) | Some(Node::ImplItem(&ImplItem { ident, .. })) => {
431             Some(ident.name)
432         },
433         _ => None,
434     }
435 }
436
437 /// Gets the name of a `Pat`, if any.
438 pub fn get_pat_name(pat: &Pat) -> Option<Name> {
439     match pat.kind {
440         PatKind::Binding(.., ref spname, _) => Some(spname.name),
441         PatKind::Path(ref qpath) => single_segment_path(qpath).map(|ps| ps.ident.name),
442         PatKind::Box(ref p) | PatKind::Ref(ref p, _) => get_pat_name(&*p),
443         _ => None,
444     }
445 }
446
447 struct ContainsName {
448     name: Name,
449     result: bool,
450 }
451
452 impl<'tcx> Visitor<'tcx> for ContainsName {
453     fn visit_name(&mut self, _: Span, name: Name) {
454         if self.name == name {
455             self.result = true;
456         }
457     }
458     fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'tcx> {
459         NestedVisitorMap::None
460     }
461 }
462
463 /// Checks if an `Expr` contains a certain name.
464 pub fn contains_name(name: Name, expr: &Expr) -> bool {
465     let mut cn = ContainsName { name, result: false };
466     cn.visit_expr(expr);
467     cn.result
468 }
469
470 /// Converts a span to a code snippet if available, otherwise use default.
471 ///
472 /// This is useful if you want to provide suggestions for your lint or more generally, if you want
473 /// to convert a given `Span` to a `str`.
474 ///
475 /// # Example
476 /// ```rust,ignore
477 /// snippet(cx, expr.span, "..")
478 /// ```
479 pub fn snippet<'a, T: LintContext>(cx: &T, span: Span, default: &'a str) -> Cow<'a, str> {
480     snippet_opt(cx, span).map_or_else(|| Cow::Borrowed(default), From::from)
481 }
482
483 /// Same as `snippet`, but it adapts the applicability level by following rules:
484 ///
485 /// - Applicability level `Unspecified` will never be changed.
486 /// - If the span is inside a macro, change the applicability level to `MaybeIncorrect`.
487 /// - If the default value is used and the applicability level is `MachineApplicable`, change it to
488 /// `HasPlaceholders`
489 pub fn snippet_with_applicability<'a, T: LintContext>(
490     cx: &T,
491     span: Span,
492     default: &'a str,
493     applicability: &mut Applicability,
494 ) -> Cow<'a, str> {
495     if *applicability != Applicability::Unspecified && span.from_expansion() {
496         *applicability = Applicability::MaybeIncorrect;
497     }
498     snippet_opt(cx, span).map_or_else(
499         || {
500             if *applicability == Applicability::MachineApplicable {
501                 *applicability = Applicability::HasPlaceholders;
502             }
503             Cow::Borrowed(default)
504         },
505         From::from,
506     )
507 }
508
509 /// Same as `snippet`, but should only be used when it's clear that the input span is
510 /// not a macro argument.
511 pub fn snippet_with_macro_callsite<'a, T: LintContext>(cx: &T, span: Span, default: &'a str) -> Cow<'a, str> {
512     snippet(cx, span.source_callsite(), default)
513 }
514
515 /// Converts a span to a code snippet. Returns `None` if not available.
516 pub fn snippet_opt<T: LintContext>(cx: &T, span: Span) -> Option<String> {
517     cx.sess().source_map().span_to_snippet(span).ok()
518 }
519
520 /// Converts a span (from a block) to a code snippet if available, otherwise use
521 /// default.
522 /// This trims the code of indentation, except for the first line. Use it for
523 /// blocks or block-like
524 /// things which need to be printed as such.
525 ///
526 /// # Example
527 /// ```rust,ignore
528 /// snippet_block(cx, expr.span, "..")
529 /// ```
530 pub fn snippet_block<'a, T: LintContext>(cx: &T, span: Span, default: &'a str) -> Cow<'a, str> {
531     let snip = snippet(cx, span, default);
532     trim_multiline(snip, true)
533 }
534
535 /// Same as `snippet_block`, but adapts the applicability level by the rules of
536 /// `snippet_with_applicabiliy`.
537 pub fn snippet_block_with_applicability<'a, T: LintContext>(
538     cx: &T,
539     span: Span,
540     default: &'a str,
541     applicability: &mut Applicability,
542 ) -> Cow<'a, str> {
543     let snip = snippet_with_applicability(cx, span, default, applicability);
544     trim_multiline(snip, true)
545 }
546
547 /// Returns a new Span that covers the full last line of the given Span
548 pub fn last_line_of_span<T: LintContext>(cx: &T, span: Span) -> Span {
549     let source_map_and_line = cx.sess().source_map().lookup_line(span.lo()).unwrap();
550     let line_no = source_map_and_line.line;
551     let line_start = &source_map_and_line.sf.lines[line_no];
552     Span::new(*line_start, span.hi(), span.ctxt())
553 }
554
555 /// Like `snippet_block`, but add braces if the expr is not an `ExprKind::Block`.
556 /// Also takes an `Option<String>` which can be put inside the braces.
557 pub fn expr_block<'a, T: LintContext>(cx: &T, expr: &Expr, option: Option<String>, default: &'a str) -> Cow<'a, str> {
558     let code = snippet_block(cx, expr.span, default);
559     let string = option.unwrap_or_default();
560     if expr.span.from_expansion() {
561         Cow::Owned(format!("{{ {} }}", snippet_with_macro_callsite(cx, expr.span, default)))
562     } else if let ExprKind::Block(_, _) = expr.kind {
563         Cow::Owned(format!("{}{}", code, string))
564     } else if string.is_empty() {
565         Cow::Owned(format!("{{ {} }}", code))
566     } else {
567         Cow::Owned(format!("{{\n{};\n{}\n}}", code, string))
568     }
569 }
570
571 /// Trim indentation from a multiline string with possibility of ignoring the
572 /// first line.
573 pub fn trim_multiline(s: Cow<'_, str>, ignore_first: bool) -> Cow<'_, str> {
574     let s_space = trim_multiline_inner(s, ignore_first, ' ');
575     let s_tab = trim_multiline_inner(s_space, ignore_first, '\t');
576     trim_multiline_inner(s_tab, ignore_first, ' ')
577 }
578
579 fn trim_multiline_inner(s: Cow<'_, str>, ignore_first: bool, ch: char) -> Cow<'_, str> {
580     let x = s
581         .lines()
582         .skip(ignore_first as usize)
583         .filter_map(|l| {
584             if l.is_empty() {
585                 None
586             } else {
587                 // ignore empty lines
588                 Some(l.char_indices().find(|&(_, x)| x != ch).unwrap_or((l.len(), ch)).0)
589             }
590         })
591         .min()
592         .unwrap_or(0);
593     if x > 0 {
594         Cow::Owned(
595             s.lines()
596                 .enumerate()
597                 .map(|(i, l)| {
598                     if (ignore_first && i == 0) || l.is_empty() {
599                         l
600                     } else {
601                         l.split_at(x).1
602                     }
603                 })
604                 .collect::<Vec<_>>()
605                 .join("\n"),
606         )
607     } else {
608         s
609     }
610 }
611
612 /// Gets the parent expression, if any â€“- this is useful to constrain a lint.
613 pub fn get_parent_expr<'c>(cx: &'c LateContext<'_, '_>, e: &Expr) -> Option<&'c Expr> {
614     let map = &cx.tcx.hir();
615     let hir_id = e.hir_id;
616     let parent_id = map.get_parent_node(hir_id);
617     if hir_id == parent_id {
618         return None;
619     }
620     map.find(parent_id).and_then(|node| {
621         if let Node::Expr(parent) = node {
622             Some(parent)
623         } else {
624             None
625         }
626     })
627 }
628
629 pub fn get_enclosing_block<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, hir_id: HirId) -> Option<&'tcx Block> {
630     let map = &cx.tcx.hir();
631     let enclosing_node = map
632         .get_enclosing_scope(hir_id)
633         .and_then(|enclosing_id| map.find(enclosing_id));
634     if let Some(node) = enclosing_node {
635         match node {
636             Node::Block(block) => Some(block),
637             Node::Item(&Item {
638                 kind: ItemKind::Fn(_, _, eid),
639                 ..
640             })
641             | Node::ImplItem(&ImplItem {
642                 kind: ImplItemKind::Method(_, eid),
643                 ..
644             }) => match cx.tcx.hir().body(eid).value.kind {
645                 ExprKind::Block(ref block, _) => Some(block),
646                 _ => None,
647             },
648             _ => None,
649         }
650     } else {
651         None
652     }
653 }
654
655 /// Returns the base type for HIR references and pointers.
656 pub fn walk_ptrs_hir_ty(ty: &hir::Ty) -> &hir::Ty {
657     match ty.kind {
658         TyKind::Ptr(ref mut_ty) | TyKind::Rptr(_, ref mut_ty) => walk_ptrs_hir_ty(&mut_ty.ty),
659         _ => ty,
660     }
661 }
662
663 /// Returns the base type for references and raw pointers.
664 pub fn walk_ptrs_ty(ty: Ty<'_>) -> Ty<'_> {
665     match ty.kind {
666         ty::Ref(_, ty, _) => walk_ptrs_ty(ty),
667         _ => ty,
668     }
669 }
670
671 /// Returns the base type for references and raw pointers, and count reference
672 /// depth.
673 pub fn walk_ptrs_ty_depth(ty: Ty<'_>) -> (Ty<'_>, usize) {
674     fn inner(ty: Ty<'_>, depth: usize) -> (Ty<'_>, usize) {
675         match ty.kind {
676             ty::Ref(_, ty, _) => inner(ty, depth + 1),
677             _ => (ty, depth),
678         }
679     }
680     inner(ty, 0)
681 }
682
683 /// Checks whether the given expression is a constant integer of the given value.
684 /// unlike `is_integer_literal`, this version does const folding
685 pub fn is_integer_const(cx: &LateContext<'_, '_>, e: &Expr, value: u128) -> bool {
686     if is_integer_literal(e, value) {
687         return true;
688     }
689     let map = cx.tcx.hir();
690     let parent_item = map.get_parent_item(e.hir_id);
691     if let Some((Constant::Int(v), _)) = map
692         .maybe_body_owned_by(parent_item)
693         .and_then(|body_id| constant(cx, cx.tcx.body_tables(body_id), e))
694     {
695         value == v
696     } else {
697         false
698     }
699 }
700
701 /// Checks whether the given expression is a constant literal of the given value.
702 pub fn is_integer_literal(expr: &Expr, value: u128) -> bool {
703     // FIXME: use constant folding
704     if let ExprKind::Lit(ref spanned) = expr.kind {
705         if let LitKind::Int(v, _) = spanned.node {
706             return v == value;
707         }
708     }
709     false
710 }
711
712 /// Returns `true` if the given `Expr` has been coerced before.
713 ///
714 /// Examples of coercions can be found in the Nomicon at
715 /// <https://doc.rust-lang.org/nomicon/coercions.html>.
716 ///
717 /// See `rustc::ty::adjustment::Adjustment` and `rustc_typeck::check::coercion` for more
718 /// information on adjustments and coercions.
719 pub fn is_adjusted(cx: &LateContext<'_, '_>, e: &Expr) -> bool {
720     cx.tables.adjustments().get(e.hir_id).is_some()
721 }
722
723 /// Returns the pre-expansion span if is this comes from an expansion of the
724 /// macro `name`.
725 /// See also `is_direct_expn_of`.
726 #[must_use]
727 pub fn is_expn_of(mut span: Span, name: &str) -> Option<Span> {
728     loop {
729         if span.from_expansion() {
730             let data = span.ctxt().outer_expn_data();
731             let mac_name = data.kind.descr();
732             let new_span = data.call_site;
733
734             if mac_name.as_str() == name {
735                 return Some(new_span);
736             } else {
737                 span = new_span;
738             }
739         } else {
740             return None;
741         }
742     }
743 }
744
745 /// Returns the pre-expansion span if the span directly comes from an expansion
746 /// of the macro `name`.
747 /// The difference with `is_expn_of` is that in
748 /// ```rust,ignore
749 /// foo!(bar!(42));
750 /// ```
751 /// `42` is considered expanded from `foo!` and `bar!` by `is_expn_of` but only
752 /// `bar!` by
753 /// `is_direct_expn_of`.
754 #[must_use]
755 pub fn is_direct_expn_of(span: Span, name: &str) -> Option<Span> {
756     if span.from_expansion() {
757         let data = span.ctxt().outer_expn_data();
758         let mac_name = data.kind.descr();
759         let new_span = data.call_site;
760
761         if mac_name.as_str() == name {
762             Some(new_span)
763         } else {
764             None
765         }
766     } else {
767         None
768     }
769 }
770
771 /// Convenience function to get the return type of a function.
772 pub fn return_ty<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, fn_item: hir::HirId) -> Ty<'tcx> {
773     let fn_def_id = cx.tcx.hir().local_def_id(fn_item);
774     let ret_ty = cx.tcx.fn_sig(fn_def_id).output();
775     cx.tcx.erase_late_bound_regions(&ret_ty)
776 }
777
778 /// Checks if two types are the same.
779 ///
780 /// This discards any lifetime annotations, too.
781 //
782 // FIXME: this works correctly for lifetimes bounds (`for <'a> Foo<'a>` ==
783 // `for <'b> Foo<'b>`, but not for type parameters).
784 pub fn same_tys<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, a: Ty<'tcx>, b: Ty<'tcx>) -> bool {
785     let a = cx.tcx.erase_late_bound_regions(&Binder::bind(a));
786     let b = cx.tcx.erase_late_bound_regions(&Binder::bind(b));
787     cx.tcx
788         .infer_ctxt()
789         .enter(|infcx| infcx.can_eq(cx.param_env, a, b).is_ok())
790 }
791
792 /// Returns `true` if the given type is an `unsafe` function.
793 pub fn type_is_unsafe_function<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, ty: Ty<'tcx>) -> bool {
794     match ty.kind {
795         ty::FnDef(..) | ty::FnPtr(_) => ty.fn_sig(cx.tcx).unsafety() == Unsafety::Unsafe,
796         _ => false,
797     }
798 }
799
800 pub fn is_copy<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, ty: Ty<'tcx>) -> bool {
801     ty.is_copy_modulo_regions(cx.tcx, cx.param_env, DUMMY_SP)
802 }
803
804 /// Checks if an expression is constructing a tuple-like enum variant or struct
805 pub fn is_ctor_or_promotable_const_function(cx: &LateContext<'_, '_>, expr: &Expr) -> bool {
806     if let ExprKind::Call(ref fun, _) = expr.kind {
807         if let ExprKind::Path(ref qp) = fun.kind {
808             let res = cx.tables.qpath_res(qp, fun.hir_id);
809             return match res {
810                 def::Res::Def(DefKind::Variant, ..) | Res::Def(DefKind::Ctor(..), _) => true,
811                 def::Res::Def(_, def_id) => cx.tcx.is_promotable_const_fn(def_id),
812                 _ => false,
813             };
814         }
815     }
816     false
817 }
818
819 /// Returns `true` if a pattern is refutable.
820 pub fn is_refutable(cx: &LateContext<'_, '_>, pat: &Pat) -> bool {
821     fn is_enum_variant(cx: &LateContext<'_, '_>, qpath: &QPath, id: HirId) -> bool {
822         matches!(
823             cx.tables.qpath_res(qpath, id),
824             def::Res::Def(DefKind::Variant, ..) | Res::Def(DefKind::Ctor(def::CtorOf::Variant, _), _)
825         )
826     }
827
828     fn are_refutable<'a, I: Iterator<Item = &'a Pat>>(cx: &LateContext<'_, '_>, mut i: I) -> bool {
829         i.any(|pat| is_refutable(cx, pat))
830     }
831
832     match pat.kind {
833         PatKind::Binding(..) | PatKind::Wild => false,
834         PatKind::Box(ref pat) | PatKind::Ref(ref pat, _) => is_refutable(cx, pat),
835         PatKind::Lit(..) | PatKind::Range(..) => true,
836         PatKind::Path(ref qpath) => is_enum_variant(cx, qpath, pat.hir_id),
837         PatKind::Or(ref pats) | PatKind::Tuple(ref pats, _) => are_refutable(cx, pats.iter().map(|pat| &**pat)),
838         PatKind::Struct(ref qpath, ref fields, _) => {
839             if is_enum_variant(cx, qpath, pat.hir_id) {
840                 true
841             } else {
842                 are_refutable(cx, fields.iter().map(|field| &*field.pat))
843             }
844         },
845         PatKind::TupleStruct(ref qpath, ref pats, _) => {
846             if is_enum_variant(cx, qpath, pat.hir_id) {
847                 true
848             } else {
849                 are_refutable(cx, pats.iter().map(|pat| &**pat))
850             }
851         },
852         PatKind::Slice(ref head, ref middle, ref tail) => {
853             are_refutable(cx, head.iter().chain(middle).chain(tail.iter()).map(|pat| &**pat))
854         },
855     }
856 }
857
858 /// Checks for the `#[automatically_derived]` attribute all `#[derive]`d
859 /// implementations have.
860 pub fn is_automatically_derived(attrs: &[ast::Attribute]) -> bool {
861     attr::contains_name(attrs, sym!(automatically_derived))
862 }
863
864 /// Remove blocks around an expression.
865 ///
866 /// Ie. `x`, `{ x }` and `{{{{ x }}}}` all give `x`. `{ x; y }` and `{}` return
867 /// themselves.
868 pub fn remove_blocks(expr: &Expr) -> &Expr {
869     if let ExprKind::Block(ref block, _) = expr.kind {
870         if block.stmts.is_empty() {
871             if let Some(ref expr) = block.expr {
872                 remove_blocks(expr)
873             } else {
874                 expr
875             }
876         } else {
877             expr
878         }
879     } else {
880         expr
881     }
882 }
883
884 pub fn is_self(slf: &Param) -> bool {
885     if let PatKind::Binding(.., name, _) = slf.pat.kind {
886         name.name == kw::SelfLower
887     } else {
888         false
889     }
890 }
891
892 pub fn is_self_ty(slf: &hir::Ty) -> bool {
893     if_chain! {
894         if let TyKind::Path(ref qp) = slf.kind;
895         if let QPath::Resolved(None, ref path) = *qp;
896         if let Res::SelfTy(..) = path.res;
897         then {
898             return true
899         }
900     }
901     false
902 }
903
904 pub fn iter_input_pats<'tcx>(decl: &FnDecl, body: &'tcx Body) -> impl Iterator<Item = &'tcx Param> {
905     (0..decl.inputs.len()).map(move |i| &body.params[i])
906 }
907
908 /// Checks if a given expression is a match expression expanded from the `?`
909 /// operator or the `try` macro.
910 pub fn is_try(expr: &Expr) -> Option<&Expr> {
911     fn is_ok(arm: &Arm) -> bool {
912         if_chain! {
913             if let PatKind::TupleStruct(ref path, ref pat, None) = arm.pat.kind;
914             if match_qpath(path, &paths::RESULT_OK[1..]);
915             if let PatKind::Binding(_, hir_id, _, None) = pat[0].kind;
916             if let ExprKind::Path(QPath::Resolved(None, ref path)) = arm.body.kind;
917             if let Res::Local(lid) = path.res;
918             if lid == hir_id;
919             then {
920                 return true;
921             }
922         }
923         false
924     }
925
926     fn is_err(arm: &Arm) -> bool {
927         if let PatKind::TupleStruct(ref path, _, _) = arm.pat.kind {
928             match_qpath(path, &paths::RESULT_ERR[1..])
929         } else {
930             false
931         }
932     }
933
934     if let ExprKind::Match(_, ref arms, ref source) = expr.kind {
935         // desugared from a `?` operator
936         if let MatchSource::TryDesugar = *source {
937             return Some(expr);
938         }
939
940         if_chain! {
941             if arms.len() == 2;
942             if arms[0].guard.is_none();
943             if arms[1].guard.is_none();
944             if (is_ok(&arms[0]) && is_err(&arms[1])) ||
945                 (is_ok(&arms[1]) && is_err(&arms[0]));
946             then {
947                 return Some(expr);
948             }
949         }
950     }
951
952     None
953 }
954
955 /// Returns `true` if the lint is allowed in the current context
956 ///
957 /// Useful for skipping long running code when it's unnecessary
958 pub fn is_allowed(cx: &LateContext<'_, '_>, lint: &'static Lint, id: HirId) -> bool {
959     cx.tcx.lint_level_at_node(lint, id).0 == Level::Allow
960 }
961
962 pub fn get_arg_name(pat: &Pat) -> Option<ast::Name> {
963     match pat.kind {
964         PatKind::Binding(.., ident, None) => Some(ident.name),
965         PatKind::Ref(ref subpat, _) => get_arg_name(subpat),
966         _ => None,
967     }
968 }
969
970 pub fn int_bits(tcx: TyCtxt<'_>, ity: ast::IntTy) -> u64 {
971     layout::Integer::from_attr(&tcx, attr::IntType::SignedInt(ity))
972         .size()
973         .bits()
974 }
975
976 #[allow(clippy::cast_possible_wrap)]
977 /// Turn a constant int byte representation into an i128
978 pub fn sext(tcx: TyCtxt<'_>, u: u128, ity: ast::IntTy) -> i128 {
979     let amt = 128 - int_bits(tcx, ity);
980     ((u as i128) << amt) >> amt
981 }
982
983 #[allow(clippy::cast_sign_loss)]
984 /// clip unused bytes
985 pub fn unsext(tcx: TyCtxt<'_>, u: i128, ity: ast::IntTy) -> u128 {
986     let amt = 128 - int_bits(tcx, ity);
987     ((u as u128) << amt) >> amt
988 }
989
990 /// clip unused bytes
991 pub fn clip(tcx: TyCtxt<'_>, u: u128, ity: ast::UintTy) -> u128 {
992     let bits = layout::Integer::from_attr(&tcx, attr::IntType::UnsignedInt(ity))
993         .size()
994         .bits();
995     let amt = 128 - bits;
996     (u << amt) >> amt
997 }
998
999 /// Removes block comments from the given `Vec` of lines.
1000 ///
1001 /// # Examples
1002 ///
1003 /// ```rust,ignore
1004 /// without_block_comments(vec!["/*", "foo", "*/"]);
1005 /// // => vec![]
1006 ///
1007 /// without_block_comments(vec!["bar", "/*", "foo", "*/"]);
1008 /// // => vec!["bar"]
1009 /// ```
1010 pub fn without_block_comments(lines: Vec<&str>) -> Vec<&str> {
1011     let mut without = vec![];
1012
1013     let mut nest_level = 0;
1014
1015     for line in lines {
1016         if line.contains("/*") {
1017             nest_level += 1;
1018             continue;
1019         } else if line.contains("*/") {
1020             nest_level -= 1;
1021             continue;
1022         }
1023
1024         if nest_level == 0 {
1025             without.push(line);
1026         }
1027     }
1028
1029     without
1030 }
1031
1032 pub fn any_parent_is_automatically_derived(tcx: TyCtxt<'_>, node: HirId) -> bool {
1033     let map = &tcx.hir();
1034     let mut prev_enclosing_node = None;
1035     let mut enclosing_node = node;
1036     while Some(enclosing_node) != prev_enclosing_node {
1037         if is_automatically_derived(map.attrs(enclosing_node)) {
1038             return true;
1039         }
1040         prev_enclosing_node = Some(enclosing_node);
1041         enclosing_node = map.get_parent_item(enclosing_node);
1042     }
1043     false
1044 }
1045
1046 /// Returns true if ty has `iter` or `iter_mut` methods
1047 pub fn has_iter_method(cx: &LateContext<'_, '_>, probably_ref_ty: Ty<'_>) -> Option<&'static str> {
1048     // FIXME: instead of this hard-coded list, we should check if `<adt>::iter`
1049     // exists and has the desired signature. Unfortunately FnCtxt is not exported
1050     // so we can't use its `lookup_method` method.
1051     let into_iter_collections: [&[&str]; 13] = [
1052         &paths::VEC,
1053         &paths::OPTION,
1054         &paths::RESULT,
1055         &paths::BTREESET,
1056         &paths::BTREEMAP,
1057         &paths::VEC_DEQUE,
1058         &paths::LINKED_LIST,
1059         &paths::BINARY_HEAP,
1060         &paths::HASHSET,
1061         &paths::HASHMAP,
1062         &paths::PATH_BUF,
1063         &paths::PATH,
1064         &paths::RECEIVER,
1065     ];
1066
1067     let ty_to_check = match probably_ref_ty.kind {
1068         ty::Ref(_, ty_to_check, _) => ty_to_check,
1069         _ => probably_ref_ty,
1070     };
1071
1072     let def_id = match ty_to_check.kind {
1073         ty::Array(..) => return Some("array"),
1074         ty::Slice(..) => return Some("slice"),
1075         ty::Adt(adt, _) => adt.did,
1076         _ => return None,
1077     };
1078
1079     for path in &into_iter_collections {
1080         if match_def_path(cx, def_id, path) {
1081             return Some(*path.last().unwrap());
1082         }
1083     }
1084     None
1085 }
1086
1087 /// Matches a function call with the given path and returns the arguments.
1088 ///
1089 /// Usage:
1090 ///
1091 /// ```rust,ignore
1092 /// if let Some(args) = match_function_call(cx, begin_panic_call, &paths::BEGIN_PANIC);
1093 /// ```
1094 pub fn match_function_call<'a, 'tcx>(
1095     cx: &LateContext<'a, 'tcx>,
1096     expr: &'tcx Expr,
1097     path: &[&str],
1098 ) -> Option<&'tcx [Expr]> {
1099     if_chain! {
1100         if let ExprKind::Call(ref fun, ref args) = expr.kind;
1101         if let ExprKind::Path(ref qpath) = fun.kind;
1102         if let Some(fun_def_id) = cx.tables.qpath_res(qpath, fun.hir_id).opt_def_id();
1103         if match_def_path(cx, fun_def_id, path);
1104         then {
1105             return Some(&args)
1106         }
1107     };
1108     None
1109 }
1110
1111 #[cfg(test)]
1112 mod test {
1113     use super::{trim_multiline, without_block_comments};
1114
1115     #[test]
1116     fn test_trim_multiline_single_line() {
1117         assert_eq!("", trim_multiline("".into(), false));
1118         assert_eq!("...", trim_multiline("...".into(), false));
1119         assert_eq!("...", trim_multiline("    ...".into(), false));
1120         assert_eq!("...", trim_multiline("\t...".into(), false));
1121         assert_eq!("...", trim_multiline("\t\t...".into(), false));
1122     }
1123
1124     #[test]
1125     #[rustfmt::skip]
1126     fn test_trim_multiline_block() {
1127         assert_eq!("\
1128     if x {
1129         y
1130     } else {
1131         z
1132     }", trim_multiline("    if x {
1133             y
1134         } else {
1135             z
1136         }".into(), false));
1137         assert_eq!("\
1138     if x {
1139     \ty
1140     } else {
1141     \tz
1142     }", trim_multiline("    if x {
1143         \ty
1144         } else {
1145         \tz
1146         }".into(), false));
1147     }
1148
1149     #[test]
1150     #[rustfmt::skip]
1151     fn test_trim_multiline_empty_line() {
1152         assert_eq!("\
1153     if x {
1154         y
1155
1156     } else {
1157         z
1158     }", trim_multiline("    if x {
1159             y
1160
1161         } else {
1162             z
1163         }".into(), false));
1164     }
1165
1166     #[test]
1167     fn test_without_block_comments_lines_without_block_comments() {
1168         let result = without_block_comments(vec!["/*", "", "*/"]);
1169         println!("result: {:?}", result);
1170         assert!(result.is_empty());
1171
1172         let result = without_block_comments(vec!["", "/*", "", "*/", "#[crate_type = \"lib\"]", "/*", "", "*/", ""]);
1173         assert_eq!(result, vec!["", "#[crate_type = \"lib\"]", ""]);
1174
1175         let result = without_block_comments(vec!["/* rust", "", "*/"]);
1176         assert!(result.is_empty());
1177
1178         let result = without_block_comments(vec!["/* one-line comment */"]);
1179         assert!(result.is_empty());
1180
1181         let result = without_block_comments(vec!["/* nested", "/* multi-line", "comment", "*/", "test", "*/"]);
1182         assert!(result.is_empty());
1183
1184         let result = without_block_comments(vec!["/* nested /* inline /* comment */ test */ */"]);
1185         assert!(result.is_empty());
1186
1187         let result = without_block_comments(vec!["foo", "bar", "baz"]);
1188         assert_eq!(result, vec!["foo", "bar", "baz"]);
1189     }
1190 }
1191
1192 pub fn match_def_path<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, did: DefId, syms: &[&str]) -> bool {
1193     let path = cx.get_def_path(did);
1194     path.len() == syms.len() && path.into_iter().zip(syms.iter()).all(|(a, &b)| a.as_str() == b)
1195 }
1196
1197 /// Returns the list of condition expressions and the list of blocks in a
1198 /// sequence of `if/else`.
1199 /// E.g., this returns `([a, b], [c, d, e])` for the expression
1200 /// `if a { c } else if b { d } else { e }`.
1201 pub fn if_sequence(mut expr: &Expr) -> (SmallVec<[&Expr; 1]>, SmallVec<[&Block; 1]>) {
1202     let mut conds = SmallVec::new();
1203     let mut blocks: SmallVec<[&Block; 1]> = SmallVec::new();
1204
1205     while let Some((ref cond, ref then_expr, ref else_expr)) = higher::if_block(&expr) {
1206         conds.push(&**cond);
1207         if let ExprKind::Block(ref block, _) = then_expr.kind {
1208             blocks.push(block);
1209         } else {
1210             panic!("ExprKind::If node is not an ExprKind::Block");
1211         }
1212
1213         if let Some(ref else_expr) = *else_expr {
1214             expr = else_expr;
1215         } else {
1216             break;
1217         }
1218     }
1219
1220     // final `else {..}`
1221     if !blocks.is_empty() {
1222         if let ExprKind::Block(ref block, _) = expr.kind {
1223             blocks.push(&**block);
1224         }
1225     }
1226
1227     (conds, blocks)
1228 }
1229
1230 pub fn parent_node_is_if_expr<'a, 'b>(expr: &Expr, cx: &LateContext<'a, 'b>) -> bool {
1231     let parent_id = cx.tcx.hir().get_parent_node(expr.hir_id);
1232     let parent_node = cx.tcx.hir().get(parent_id);
1233
1234     match parent_node {
1235         rustc::hir::Node::Expr(e) => higher::if_block(&e).is_some(),
1236         rustc::hir::Node::Arm(e) => higher::if_block(&e.body).is_some(),
1237         _ => false,
1238     }
1239 }