]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/utils/mod.rs
Merge branch 'master' into fix-3739
[rust.git] / clippy_lints / src / utils / mod.rs
1 pub mod attrs;
2 pub mod author;
3 pub mod camel_case;
4 pub mod comparisons;
5 pub mod conf;
6 pub mod constants;
7 mod diagnostics;
8 pub mod higher;
9 mod hir_utils;
10 pub mod inspector;
11 pub mod internal_lints;
12 pub mod paths;
13 pub mod ptr;
14 pub mod sugg;
15 pub mod usage;
16 pub use self::attrs::*;
17 pub use self::diagnostics::*;
18 pub use self::hir_utils::{SpanlessEq, SpanlessHash};
19
20 use std::borrow::Cow;
21 use std::mem;
22
23 use if_chain::if_chain;
24 use matches::matches;
25 use rustc::hir;
26 use rustc::hir::def::Def;
27 use rustc::hir::def_id::{DefId, CRATE_DEF_INDEX, LOCAL_CRATE};
28 use rustc::hir::intravisit::{NestedVisitorMap, Visitor};
29 use rustc::hir::Node;
30 use rustc::hir::*;
31 use rustc::lint::{LateContext, Level, Lint, LintContext};
32 use rustc::traits;
33 use rustc::ty::{
34     self,
35     layout::{self, IntegerExt},
36     subst::Kind,
37     Binder, Ty, TyCtxt,
38 };
39 use rustc_data_structures::sync::Lrc;
40 use rustc_errors::Applicability;
41 use syntax::ast::{self, LitKind};
42 use syntax::attr;
43 use syntax::source_map::{Span, DUMMY_SP};
44 use syntax::symbol;
45 use syntax::symbol::{keywords, Symbol};
46
47 use crate::reexport::*;
48
49 /// Returns `true` if the two spans come from differing expansions (i.e., one is
50 /// from a macro and one isn't).
51 pub fn differing_macro_contexts(lhs: Span, rhs: Span) -> bool {
52     rhs.ctxt() != lhs.ctxt()
53 }
54
55 /// Returns `true` if the given `NodeId` is inside a constant context
56 ///
57 /// # Example
58 ///
59 /// ```rust,ignore
60 /// if in_constant(cx, expr.id) {
61 ///     // Do something
62 /// }
63 /// ```
64 pub fn in_constant(cx: &LateContext<'_, '_>, id: HirId) -> bool {
65     let parent_id = cx.tcx.hir().get_parent_item(id);
66     match cx.tcx.hir().get_by_hir_id(parent_id) {
67         Node::Item(&Item {
68             node: ItemKind::Const(..),
69             ..
70         })
71         | Node::TraitItem(&TraitItem {
72             node: TraitItemKind::Const(..),
73             ..
74         })
75         | Node::ImplItem(&ImplItem {
76             node: ImplItemKind::Const(..),
77             ..
78         })
79         | Node::AnonConst(_)
80         | Node::Item(&Item {
81             node: ItemKind::Static(..),
82             ..
83         }) => true,
84         Node::Item(&Item {
85             node: ItemKind::Fn(_, header, ..),
86             ..
87         }) => header.constness == Constness::Const,
88         _ => false,
89     }
90 }
91
92 /// Returns `true` if this `expn_info` was expanded by any macro.
93 pub fn in_macro(span: Span) -> bool {
94     span.ctxt().outer().expn_info().is_some()
95 }
96
97 /// Used to store the absolute path to a type.
98 ///
99 /// See `match_def_path` for usage.
100 #[derive(Debug)]
101 pub struct AbsolutePathBuffer {
102     pub names: Vec<symbol::LocalInternedString>,
103 }
104
105 impl ty::item_path::ItemPathBuffer for AbsolutePathBuffer {
106     fn root_mode(&self) -> &ty::item_path::RootMode {
107         const ABSOLUTE: &ty::item_path::RootMode = &ty::item_path::RootMode::Absolute;
108         ABSOLUTE
109     }
110
111     fn push(&mut self, text: &str) {
112         self.names.push(symbol::Symbol::intern(text).as_str());
113     }
114 }
115
116 /// Checks if a `DefId`'s path matches the given absolute type path usage.
117 ///
118 /// # Examples
119 /// ```rust,ignore
120 /// match_def_path(cx.tcx, id, &["core", "option", "Option"])
121 /// ```
122 ///
123 /// See also the `paths` module.
124 pub fn match_def_path(tcx: TyCtxt<'_, '_, '_>, def_id: DefId, path: &[&str]) -> bool {
125     let mut apb = AbsolutePathBuffer { names: vec![] };
126
127     tcx.push_item_path(&mut apb, def_id, false);
128
129     apb.names.len() == path.len() && apb.names.into_iter().zip(path.iter()).all(|(a, &b)| *a == *b)
130 }
131
132 /// Gets the absolute path of `def_id` as a vector of `&str`.
133 ///
134 /// # Examples
135 /// ```rust,ignore
136 /// let def_path = get_def_path(tcx, def_id);
137 /// if let &["core", "option", "Option"] = &def_path[..] {
138 ///     // The given `def_id` is that of an `Option` type
139 /// };
140 /// ```
141 pub fn get_def_path(tcx: TyCtxt<'_, '_, '_>, def_id: DefId) -> Vec<&'static str> {
142     let mut apb = AbsolutePathBuffer { names: vec![] };
143     tcx.push_item_path(&mut apb, def_id, false);
144     apb.names
145         .iter()
146         .map(syntax_pos::symbol::LocalInternedString::get)
147         .collect()
148 }
149
150 /// Checks if type is struct, enum or union type with the given def path.
151 pub fn match_type(cx: &LateContext<'_, '_>, ty: Ty<'_>, path: &[&str]) -> bool {
152     match ty.sty {
153         ty::Adt(adt, _) => match_def_path(cx.tcx, adt.did, path),
154         _ => false,
155     }
156 }
157
158 /// Checks if the method call given in `expr` belongs to the given trait.
159 pub fn match_trait_method(cx: &LateContext<'_, '_>, expr: &Expr, path: &[&str]) -> bool {
160     let method_call = cx.tables.type_dependent_defs()[expr.hir_id];
161     let trt_id = cx.tcx.trait_of_item(method_call.def_id());
162     if let Some(trt_id) = trt_id {
163         match_def_path(cx.tcx, trt_id, path)
164     } else {
165         false
166     }
167 }
168
169 /// Checks if an expression references a variable of the given name.
170 pub fn match_var(expr: &Expr, var: Name) -> bool {
171     if let ExprKind::Path(QPath::Resolved(None, ref path)) = expr.node {
172         if path.segments.len() == 1 && path.segments[0].ident.name == var {
173             return true;
174         }
175     }
176     false
177 }
178
179 pub fn last_path_segment(path: &QPath) -> &PathSegment {
180     match *path {
181         QPath::Resolved(_, ref path) => path.segments.last().expect("A path must have at least one segment"),
182         QPath::TypeRelative(_, ref seg) => seg,
183     }
184 }
185
186 pub fn single_segment_path(path: &QPath) -> Option<&PathSegment> {
187     match *path {
188         QPath::Resolved(_, ref path) if path.segments.len() == 1 => Some(&path.segments[0]),
189         QPath::Resolved(..) => None,
190         QPath::TypeRelative(_, ref seg) => Some(seg),
191     }
192 }
193
194 /// Matches a `QPath` against a slice of segment string literals.
195 ///
196 /// There is also `match_path` if you are dealing with a `rustc::hir::Path` instead of a
197 /// `rustc::hir::QPath`.
198 ///
199 /// # Examples
200 /// ```rust,ignore
201 /// match_qpath(path, &["std", "rt", "begin_unwind"])
202 /// ```
203 pub fn match_qpath(path: &QPath, segments: &[&str]) -> bool {
204     match *path {
205         QPath::Resolved(_, ref path) => match_path(path, segments),
206         QPath::TypeRelative(ref ty, ref segment) => match ty.node {
207             TyKind::Path(ref inner_path) => {
208                 !segments.is_empty()
209                     && match_qpath(inner_path, &segments[..(segments.len() - 1)])
210                     && segment.ident.name == segments[segments.len() - 1]
211             },
212             _ => false,
213         },
214     }
215 }
216
217 /// Matches a `Path` against a slice of segment string literals.
218 ///
219 /// There is also `match_qpath` if you are dealing with a `rustc::hir::QPath` instead of a
220 /// `rustc::hir::Path`.
221 ///
222 /// # Examples
223 ///
224 /// ```rust,ignore
225 /// if match_path(&trait_ref.path, &paths::HASH) {
226 ///     // This is the `std::hash::Hash` trait.
227 /// }
228 ///
229 /// if match_path(ty_path, &["rustc", "lint", "Lint"]) {
230 ///     // This is a `rustc::lint::Lint`.
231 /// }
232 /// ```
233 pub fn match_path(path: &Path, segments: &[&str]) -> bool {
234     path.segments
235         .iter()
236         .rev()
237         .zip(segments.iter().rev())
238         .all(|(a, b)| a.ident.name == *b)
239 }
240
241 /// Matches a `Path` against a slice of segment string literals, e.g.
242 ///
243 /// # Examples
244 /// ```rust,ignore
245 /// match_qpath(path, &["std", "rt", "begin_unwind"])
246 /// ```
247 pub fn match_path_ast(path: &ast::Path, segments: &[&str]) -> bool {
248     path.segments
249         .iter()
250         .rev()
251         .zip(segments.iter().rev())
252         .all(|(a, b)| a.ident.name == *b)
253 }
254
255 /// Gets the definition associated to a path.
256 pub fn path_to_def(cx: &LateContext<'_, '_>, path: &[&str]) -> Option<def::Def> {
257     let crates = cx.tcx.crates();
258     let krate = crates.iter().find(|&&krate| cx.tcx.crate_name(krate) == path[0]);
259     if let Some(krate) = krate {
260         let krate = DefId {
261             krate: *krate,
262             index: CRATE_DEF_INDEX,
263         };
264         let mut items = cx.tcx.item_children(krate);
265         let mut path_it = path.iter().skip(1).peekable();
266
267         loop {
268             let segment = match path_it.next() {
269                 Some(segment) => segment,
270                 None => return None,
271             };
272
273             for item in mem::replace(&mut items, Lrc::new(vec![])).iter() {
274                 if item.ident.name == *segment {
275                     if path_it.peek().is_none() {
276                         return Some(item.def);
277                     }
278
279                     items = cx.tcx.item_children(item.def.def_id());
280                     break;
281                 }
282             }
283         }
284     } else {
285         None
286     }
287 }
288
289 /// Convenience function to get the `DefId` of a trait by path.
290 pub fn get_trait_def_id(cx: &LateContext<'_, '_>, path: &[&str]) -> Option<DefId> {
291     let def = match path_to_def(cx, path) {
292         Some(def) => def,
293         None => return None,
294     };
295
296     match def {
297         def::Def::Trait(trait_id) => Some(trait_id),
298         _ => None,
299     }
300 }
301
302 /// Checks whether a type implements a trait.
303 /// See also `get_trait_def_id`.
304 pub fn implements_trait<'a, 'tcx>(
305     cx: &LateContext<'a, 'tcx>,
306     ty: Ty<'tcx>,
307     trait_id: DefId,
308     ty_params: &[Kind<'tcx>],
309 ) -> bool {
310     let ty = cx.tcx.erase_regions(&ty);
311     let obligation = cx.tcx.predicate_for_trait_def(
312         cx.param_env,
313         traits::ObligationCause::dummy(),
314         trait_id,
315         0,
316         ty,
317         ty_params,
318     );
319     cx.tcx
320         .infer_ctxt()
321         .enter(|infcx| infcx.predicate_must_hold_modulo_regions(&obligation))
322 }
323
324 /// Gets the `hir::TraitRef` of the trait the given method is implemented for.
325 ///
326 /// Use this if you want to find the `TraitRef` of the `Add` trait in this example:
327 ///
328 /// ```rust
329 /// struct Point(isize, isize);
330 ///
331 /// impl std::ops::Add for Point {
332 ///     type Output = Self;
333 ///
334 ///     fn add(self, other: Self) -> Self {
335 ///         Point(0, 0)
336 ///     }
337 /// }
338 /// ```
339 pub fn trait_ref_of_method(cx: &LateContext<'_, '_>, hir_id: HirId) -> Option<TraitRef> {
340     // Get the implemented trait for the current function
341     let parent_impl = cx.tcx.hir().get_parent_item(hir_id);
342     if_chain! {
343         if parent_impl != hir::CRATE_HIR_ID;
344         if let hir::Node::Item(item) = cx.tcx.hir().get_by_hir_id(parent_impl);
345         if let hir::ItemKind::Impl(_, _, _, _, trait_ref, _, _) = &item.node;
346         then { return trait_ref.clone(); }
347     }
348     None
349 }
350
351 /// Checks whether this type implements `Drop`.
352 pub fn has_drop<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, ty: Ty<'tcx>) -> bool {
353     match ty.ty_adt_def() {
354         Some(def) => def.has_dtor(cx.tcx),
355         _ => false,
356     }
357 }
358
359 /// Resolves the definition of a node from its `HirId`.
360 pub fn resolve_node(cx: &LateContext<'_, '_>, qpath: &QPath, id: HirId) -> def::Def {
361     cx.tables.qpath_def(qpath, id)
362 }
363
364 /// Returns the method names and argument list of nested method call expressions that make up
365 /// `expr`.
366 pub fn method_calls<'a>(expr: &'a Expr, max_depth: usize) -> (Vec<Symbol>, Vec<&'a [Expr]>) {
367     let mut method_names = Vec::with_capacity(max_depth);
368     let mut arg_lists = Vec::with_capacity(max_depth);
369
370     let mut current = expr;
371     for _ in 0..max_depth {
372         if let ExprKind::MethodCall(path, _, args) = &current.node {
373             if args.iter().any(|e| in_macro(e.span)) {
374                 break;
375             }
376             method_names.push(path.ident.name);
377             arg_lists.push(&**args);
378             current = &args[0];
379         } else {
380             break;
381         }
382     }
383
384     (method_names, arg_lists)
385 }
386
387 /// Matches an `Expr` against a chain of methods, and return the matched `Expr`s.
388 ///
389 /// For example, if `expr` represents the `.baz()` in `foo.bar().baz()`,
390 /// `matched_method_chain(expr, &["bar", "baz"])` will return a `Vec`
391 /// containing the `Expr`s for
392 /// `.bar()` and `.baz()`
393 pub fn method_chain_args<'a>(expr: &'a Expr, methods: &[&str]) -> Option<Vec<&'a [Expr]>> {
394     let mut current = expr;
395     let mut matched = Vec::with_capacity(methods.len());
396     for method_name in methods.iter().rev() {
397         // method chains are stored last -> first
398         if let ExprKind::MethodCall(ref path, _, ref args) = current.node {
399             if path.ident.name == *method_name {
400                 if args.iter().any(|e| in_macro(e.span)) {
401                     return None;
402                 }
403                 matched.push(&**args); // build up `matched` backwards
404                 current = &args[0] // go to parent expression
405             } else {
406                 return None;
407             }
408         } else {
409             return None;
410         }
411     }
412     // Reverse `matched` so that it is in the same order as `methods`.
413     matched.reverse();
414     Some(matched)
415 }
416
417 /// Returns `true` if the provided `def_id` is an entrypoint to a program.
418 pub fn is_entrypoint_fn(cx: &LateContext<'_, '_>, def_id: DefId) -> bool {
419     if let Some((entry_fn_def_id, _)) = cx.tcx.entry_fn(LOCAL_CRATE) {
420         return def_id == entry_fn_def_id;
421     }
422     false
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_by_hir_id(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.node {
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, 'b, T: LintContext<'b>>(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, 'b, T: LintContext<'b>>(
490     cx: &T,
491     span: Span,
492     default: &'a str,
493     applicability: &mut Applicability,
494 ) -> Cow<'a, str> {
495     if *applicability != Applicability::Unspecified && in_macro(span) {
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, 'b, T: LintContext<'b>>(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<'a, T: LintContext<'a>>(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, 'b, T: LintContext<'b>>(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, 'b, T: LintContext<'b>>(
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<'a, T: LintContext<'a>>(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, 'b, T: LintContext<'b>>(
558     cx: &T,
559     expr: &Expr,
560     option: Option<String>,
561     default: &'a str,
562 ) -> Cow<'a, str> {
563     let code = snippet_block(cx, expr.span, default);
564     let string = option.unwrap_or_default();
565     if in_macro(expr.span) {
566         Cow::Owned(format!("{{ {} }}", snippet_with_macro_callsite(cx, expr.span, default)))
567     } else if let ExprKind::Block(_, _) = expr.node {
568         Cow::Owned(format!("{}{}", code, string))
569     } else if string.is_empty() {
570         Cow::Owned(format!("{{ {} }}", code))
571     } else {
572         Cow::Owned(format!("{{\n{};\n{}\n}}", code, string))
573     }
574 }
575
576 /// Trim indentation from a multiline string with possibility of ignoring the
577 /// first line.
578 pub fn trim_multiline(s: Cow<'_, str>, ignore_first: bool) -> Cow<'_, str> {
579     let s_space = trim_multiline_inner(s, ignore_first, ' ');
580     let s_tab = trim_multiline_inner(s_space, ignore_first, '\t');
581     trim_multiline_inner(s_tab, ignore_first, ' ')
582 }
583
584 fn trim_multiline_inner(s: Cow<'_, str>, ignore_first: bool, ch: char) -> Cow<'_, str> {
585     let x = s
586         .lines()
587         .skip(ignore_first as usize)
588         .filter_map(|l| {
589             if l.is_empty() {
590                 None
591             } else {
592                 // ignore empty lines
593                 Some(l.char_indices().find(|&(_, x)| x != ch).unwrap_or((l.len(), ch)).0)
594             }
595         })
596         .min()
597         .unwrap_or(0);
598     if x > 0 {
599         Cow::Owned(
600             s.lines()
601                 .enumerate()
602                 .map(|(i, l)| {
603                     if (ignore_first && i == 0) || l.is_empty() {
604                         l
605                     } else {
606                         l.split_at(x).1
607                     }
608                 })
609                 .collect::<Vec<_>>()
610                 .join("\n"),
611         )
612     } else {
613         s
614     }
615 }
616
617 /// Gets the parent expression, if any â€“- this is useful to constrain a lint.
618 pub fn get_parent_expr<'c>(cx: &'c LateContext<'_, '_>, e: &Expr) -> Option<&'c Expr> {
619     let map = &cx.tcx.hir();
620     let hir_id = e.hir_id;
621     let parent_id = map.get_parent_node_by_hir_id(hir_id);
622     if hir_id == parent_id {
623         return None;
624     }
625     map.find_by_hir_id(parent_id).and_then(|node| {
626         if let Node::Expr(parent) = node {
627             Some(parent)
628         } else {
629             None
630         }
631     })
632 }
633
634 pub fn get_enclosing_block<'a, 'tcx: 'a>(cx: &LateContext<'a, 'tcx>, node: HirId) -> Option<&'tcx Block> {
635     let map = &cx.tcx.hir();
636     let node_id = map.hir_to_node_id(node);
637     let enclosing_node = map
638         .get_enclosing_scope(node_id)
639         .and_then(|enclosing_id| map.find(enclosing_id));
640     if let Some(node) = enclosing_node {
641         match node {
642             Node::Block(block) => Some(block),
643             Node::Item(&Item {
644                 node: ItemKind::Fn(_, _, _, eid),
645                 ..
646             })
647             | Node::ImplItem(&ImplItem {
648                 node: ImplItemKind::Method(_, eid),
649                 ..
650             }) => match cx.tcx.hir().body(eid).value.node {
651                 ExprKind::Block(ref block, _) => Some(block),
652                 _ => None,
653             },
654             _ => None,
655         }
656     } else {
657         None
658     }
659 }
660
661 /// Returns the base type for HIR references and pointers.
662 pub fn walk_ptrs_hir_ty(ty: &hir::Ty) -> &hir::Ty {
663     match ty.node {
664         TyKind::Ptr(ref mut_ty) | TyKind::Rptr(_, ref mut_ty) => walk_ptrs_hir_ty(&mut_ty.ty),
665         _ => ty,
666     }
667 }
668
669 /// Returns the base type for references and raw pointers.
670 pub fn walk_ptrs_ty(ty: Ty<'_>) -> Ty<'_> {
671     match ty.sty {
672         ty::Ref(_, ty, _) => walk_ptrs_ty(ty),
673         _ => ty,
674     }
675 }
676
677 /// Returns the base type for references and raw pointers, and count reference
678 /// depth.
679 pub fn walk_ptrs_ty_depth(ty: Ty<'_>) -> (Ty<'_>, usize) {
680     fn inner(ty: Ty<'_>, depth: usize) -> (Ty<'_>, usize) {
681         match ty.sty {
682             ty::Ref(_, ty, _) => inner(ty, depth + 1),
683             _ => (ty, depth),
684         }
685     }
686     inner(ty, 0)
687 }
688
689 /// Checks whether the given expression is a constant literal of the given value.
690 pub fn is_integer_literal(expr: &Expr, value: u128) -> bool {
691     // FIXME: use constant folding
692     if let ExprKind::Lit(ref spanned) = expr.node {
693         if let LitKind::Int(v, _) = spanned.node {
694             return v == value;
695         }
696     }
697     false
698 }
699
700 /// Returns `true` if the given `Expr` has been coerced before.
701 ///
702 /// Examples of coercions can be found in the Nomicon at
703 /// <https://doc.rust-lang.org/nomicon/coercions.html>.
704 ///
705 /// See `rustc::ty::adjustment::Adjustment` and `rustc_typeck::check::coercion` for more
706 /// information on adjustments and coercions.
707 pub fn is_adjusted(cx: &LateContext<'_, '_>, e: &Expr) -> bool {
708     cx.tables.adjustments().get(e.hir_id).is_some()
709 }
710
711 /// Returns the pre-expansion span if is this comes from an expansion of the
712 /// macro `name`.
713 /// See also `is_direct_expn_of`.
714 pub fn is_expn_of(mut span: Span, name: &str) -> Option<Span> {
715     loop {
716         let span_name_span = span
717             .ctxt()
718             .outer()
719             .expn_info()
720             .map(|ei| (ei.format.name(), ei.call_site));
721
722         match span_name_span {
723             Some((mac_name, new_span)) if mac_name == name => return Some(new_span),
724             None => return None,
725             Some((_, new_span)) => span = new_span,
726         }
727     }
728 }
729
730 /// Returns the pre-expansion span if the span directly comes from an expansion
731 /// of the macro `name`.
732 /// The difference with `is_expn_of` is that in
733 /// ```rust,ignore
734 /// foo!(bar!(42));
735 /// ```
736 /// `42` is considered expanded from `foo!` and `bar!` by `is_expn_of` but only
737 /// `bar!` by
738 /// `is_direct_expn_of`.
739 pub fn is_direct_expn_of(span: Span, name: &str) -> Option<Span> {
740     let span_name_span = span
741         .ctxt()
742         .outer()
743         .expn_info()
744         .map(|ei| (ei.format.name(), ei.call_site));
745
746     match span_name_span {
747         Some((mac_name, new_span)) if mac_name == name => Some(new_span),
748         _ => None,
749     }
750 }
751
752 /// Convenience function to get the return type of a function.
753 pub fn return_ty<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, fn_item: hir::HirId) -> Ty<'tcx> {
754     let fn_def_id = cx.tcx.hir().local_def_id_from_hir_id(fn_item);
755     let ret_ty = cx.tcx.fn_sig(fn_def_id).output();
756     cx.tcx.erase_late_bound_regions(&ret_ty)
757 }
758
759 /// Checks if two types are the same.
760 ///
761 /// This discards any lifetime annotations, too.
762 //
763 // FIXME: this works correctly for lifetimes bounds (`for <'a> Foo<'a>` ==
764 // `for <'b> Foo<'b>`, but not for type parameters).
765 pub fn same_tys<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, a: Ty<'tcx>, b: Ty<'tcx>) -> bool {
766     let a = cx.tcx.erase_late_bound_regions(&Binder::bind(a));
767     let b = cx.tcx.erase_late_bound_regions(&Binder::bind(b));
768     cx.tcx
769         .infer_ctxt()
770         .enter(|infcx| infcx.can_eq(cx.param_env, a, b).is_ok())
771 }
772
773 /// Returns `true` if the given type is an `unsafe` function.
774 pub fn type_is_unsafe_function<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, ty: Ty<'tcx>) -> bool {
775     match ty.sty {
776         ty::FnDef(..) | ty::FnPtr(_) => ty.fn_sig(cx.tcx).unsafety() == Unsafety::Unsafe,
777         _ => false,
778     }
779 }
780
781 pub fn is_copy<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, ty: Ty<'tcx>) -> bool {
782     ty.is_copy_modulo_regions(cx.tcx.global_tcx(), cx.param_env, DUMMY_SP)
783 }
784
785 /// Returns `true` if a pattern is refutable.
786 pub fn is_refutable(cx: &LateContext<'_, '_>, pat: &Pat) -> bool {
787     fn is_enum_variant(cx: &LateContext<'_, '_>, qpath: &QPath, id: HirId) -> bool {
788         matches!(
789             cx.tables.qpath_def(qpath, id),
790             def::Def::Variant(..) | def::Def::VariantCtor(..)
791         )
792     }
793
794     fn are_refutable<'a, I: Iterator<Item = &'a Pat>>(cx: &LateContext<'_, '_>, mut i: I) -> bool {
795         i.any(|pat| is_refutable(cx, pat))
796     }
797
798     match pat.node {
799         PatKind::Binding(..) | PatKind::Wild => false,
800         PatKind::Box(ref pat) | PatKind::Ref(ref pat, _) => is_refutable(cx, pat),
801         PatKind::Lit(..) | PatKind::Range(..) => true,
802         PatKind::Path(ref qpath) => is_enum_variant(cx, qpath, pat.hir_id),
803         PatKind::Tuple(ref pats, _) => are_refutable(cx, pats.iter().map(|pat| &**pat)),
804         PatKind::Struct(ref qpath, ref fields, _) => {
805             if is_enum_variant(cx, qpath, pat.hir_id) {
806                 true
807             } else {
808                 are_refutable(cx, fields.iter().map(|field| &*field.node.pat))
809             }
810         },
811         PatKind::TupleStruct(ref qpath, ref pats, _) => {
812             if is_enum_variant(cx, qpath, pat.hir_id) {
813                 true
814             } else {
815                 are_refutable(cx, pats.iter().map(|pat| &**pat))
816             }
817         },
818         PatKind::Slice(ref head, ref middle, ref tail) => {
819             are_refutable(cx, head.iter().chain(middle).chain(tail.iter()).map(|pat| &**pat))
820         },
821     }
822 }
823
824 /// Checks for the `#[automatically_derived]` attribute all `#[derive]`d
825 /// implementations have.
826 pub fn is_automatically_derived(attrs: &[ast::Attribute]) -> bool {
827     attr::contains_name(attrs, "automatically_derived")
828 }
829
830 /// Remove blocks around an expression.
831 ///
832 /// Ie. `x`, `{ x }` and `{{{{ x }}}}` all give `x`. `{ x; y }` and `{}` return
833 /// themselves.
834 pub fn remove_blocks(expr: &Expr) -> &Expr {
835     if let ExprKind::Block(ref block, _) = expr.node {
836         if block.stmts.is_empty() {
837             if let Some(ref expr) = block.expr {
838                 remove_blocks(expr)
839             } else {
840                 expr
841             }
842         } else {
843             expr
844         }
845     } else {
846         expr
847     }
848 }
849
850 pub fn is_self(slf: &Arg) -> bool {
851     if let PatKind::Binding(.., name, _) = slf.pat.node {
852         name.name == keywords::SelfLower.name()
853     } else {
854         false
855     }
856 }
857
858 pub fn is_self_ty(slf: &hir::Ty) -> bool {
859     if_chain! {
860         if let TyKind::Path(ref qp) = slf.node;
861         if let QPath::Resolved(None, ref path) = *qp;
862         if let Def::SelfTy(..) = path.def;
863         then {
864             return true
865         }
866     }
867     false
868 }
869
870 pub fn iter_input_pats<'tcx>(decl: &FnDecl, body: &'tcx Body) -> impl Iterator<Item = &'tcx Arg> {
871     (0..decl.inputs.len()).map(move |i| &body.arguments[i])
872 }
873
874 /// Checks if a given expression is a match expression expanded from the `?`
875 /// operator or the `try` macro.
876 pub fn is_try<'a>(cx: &'_ LateContext<'_, '_>, expr: &'a Expr) -> Option<&'a Expr> {
877     fn is_ok(cx: &'_ LateContext<'_, '_>, arm: &Arm) -> bool {
878         if_chain! {
879             if let PatKind::TupleStruct(ref path, ref pat, None) = arm.pats[0].node;
880             if match_qpath(path, &paths::RESULT_OK[1..]);
881             if let PatKind::Binding(_, hir_id, _, None) = pat[0].node;
882             if let ExprKind::Path(QPath::Resolved(None, ref path)) = arm.body.node;
883             if let Def::Local(lid) = path.def;
884             if cx.tcx.hir().node_to_hir_id(lid) == hir_id;
885             then {
886                 return true;
887             }
888         }
889         false
890     }
891
892     fn is_err(arm: &Arm) -> bool {
893         if let PatKind::TupleStruct(ref path, _, _) = arm.pats[0].node {
894             match_qpath(path, &paths::RESULT_ERR[1..])
895         } else {
896             false
897         }
898     }
899
900     if let ExprKind::Match(_, ref arms, ref source) = expr.node {
901         // desugared from a `?` operator
902         if let MatchSource::TryDesugar = *source {
903             return Some(expr);
904         }
905
906         if_chain! {
907             if arms.len() == 2;
908             if arms[0].pats.len() == 1 && arms[0].guard.is_none();
909             if arms[1].pats.len() == 1 && arms[1].guard.is_none();
910             if (is_ok(cx, &arms[0]) && is_err(&arms[1])) ||
911                 (is_ok(cx, &arms[1]) && is_err(&arms[0]));
912             then {
913                 return Some(expr);
914             }
915         }
916     }
917
918     None
919 }
920
921 /// Returns `true` if the lint is allowed in the current context
922 ///
923 /// Useful for skipping long running code when it's unnecessary
924 pub fn is_allowed(cx: &LateContext<'_, '_>, lint: &'static Lint, id: HirId) -> bool {
925     cx.tcx.lint_level_at_node(lint, id).0 == Level::Allow
926 }
927
928 pub fn get_arg_name(pat: &Pat) -> Option<ast::Name> {
929     match pat.node {
930         PatKind::Binding(.., ident, None) => Some(ident.name),
931         PatKind::Ref(ref subpat, _) => get_arg_name(subpat),
932         _ => None,
933     }
934 }
935
936 pub fn int_bits(tcx: TyCtxt<'_, '_, '_>, ity: ast::IntTy) -> u64 {
937     layout::Integer::from_attr(&tcx, attr::IntType::SignedInt(ity))
938         .size()
939         .bits()
940 }
941
942 #[allow(clippy::cast_possible_wrap)]
943 /// Turn a constant int byte representation into an i128
944 pub fn sext(tcx: TyCtxt<'_, '_, '_>, u: u128, ity: ast::IntTy) -> i128 {
945     let amt = 128 - int_bits(tcx, ity);
946     ((u as i128) << amt) >> amt
947 }
948
949 #[allow(clippy::cast_sign_loss)]
950 /// clip unused bytes
951 pub fn unsext(tcx: TyCtxt<'_, '_, '_>, u: i128, ity: ast::IntTy) -> u128 {
952     let amt = 128 - int_bits(tcx, ity);
953     ((u as u128) << amt) >> amt
954 }
955
956 /// clip unused bytes
957 pub fn clip(tcx: TyCtxt<'_, '_, '_>, u: u128, ity: ast::UintTy) -> u128 {
958     let bits = layout::Integer::from_attr(&tcx, attr::IntType::UnsignedInt(ity))
959         .size()
960         .bits();
961     let amt = 128 - bits;
962     (u << amt) >> amt
963 }
964
965 /// Removes block comments from the given `Vec` of lines.
966 ///
967 /// # Examples
968 ///
969 /// ```rust,ignore
970 /// without_block_comments(vec!["/*", "foo", "*/"]);
971 /// // => vec![]
972 ///
973 /// without_block_comments(vec!["bar", "/*", "foo", "*/"]);
974 /// // => vec!["bar"]
975 /// ```
976 pub fn without_block_comments(lines: Vec<&str>) -> Vec<&str> {
977     let mut without = vec![];
978
979     let mut nest_level = 0;
980
981     for line in lines {
982         if line.contains("/*") {
983             nest_level += 1;
984             continue;
985         } else if line.contains("*/") {
986             nest_level -= 1;
987             continue;
988         }
989
990         if nest_level == 0 {
991             without.push(line);
992         }
993     }
994
995     without
996 }
997
998 pub fn any_parent_is_automatically_derived(tcx: TyCtxt<'_, '_, '_>, node: HirId) -> bool {
999     let map = &tcx.hir();
1000     let mut prev_enclosing_node = None;
1001     let mut enclosing_node = node;
1002     while Some(enclosing_node) != prev_enclosing_node {
1003         if is_automatically_derived(map.attrs_by_hir_id(enclosing_node)) {
1004             return true;
1005         }
1006         prev_enclosing_node = Some(enclosing_node);
1007         enclosing_node = map.get_parent_item(enclosing_node);
1008     }
1009     false
1010 }
1011
1012 /// Returns true if ty has `iter` or `iter_mut` methods
1013 pub fn has_iter_method(cx: &LateContext<'_, '_>, probably_ref_ty: ty::Ty<'_>) -> Option<&'static str> {
1014     // FIXME: instead of this hard-coded list, we should check if `<adt>::iter`
1015     // exists and has the desired signature. Unfortunately FnCtxt is not exported
1016     // so we can't use its `lookup_method` method.
1017     static INTO_ITER_COLLECTIONS: [&[&str]; 13] = [
1018         &paths::VEC,
1019         &paths::OPTION,
1020         &paths::RESULT,
1021         &paths::BTREESET,
1022         &paths::BTREEMAP,
1023         &paths::VEC_DEQUE,
1024         &paths::LINKED_LIST,
1025         &paths::BINARY_HEAP,
1026         &paths::HASHSET,
1027         &paths::HASHMAP,
1028         &paths::PATH_BUF,
1029         &paths::PATH,
1030         &paths::RECEIVER,
1031     ];
1032
1033     let ty_to_check = match probably_ref_ty.sty {
1034         ty::Ref(_, ty_to_check, _) => ty_to_check,
1035         _ => probably_ref_ty,
1036     };
1037
1038     let def_id = match ty_to_check.sty {
1039         ty::Array(..) => return Some("array"),
1040         ty::Slice(..) => return Some("slice"),
1041         ty::Adt(adt, _) => adt.did,
1042         _ => return None,
1043     };
1044
1045     for path in &INTO_ITER_COLLECTIONS {
1046         if match_def_path(cx.tcx, def_id, path) {
1047             return Some(path.last().unwrap());
1048         }
1049     }
1050     None
1051 }
1052
1053 #[cfg(test)]
1054 mod test {
1055     use super::{trim_multiline, without_block_comments};
1056
1057     #[test]
1058     fn test_trim_multiline_single_line() {
1059         assert_eq!("", trim_multiline("".into(), false));
1060         assert_eq!("...", trim_multiline("...".into(), false));
1061         assert_eq!("...", trim_multiline("    ...".into(), false));
1062         assert_eq!("...", trim_multiline("\t...".into(), false));
1063         assert_eq!("...", trim_multiline("\t\t...".into(), false));
1064     }
1065
1066     #[test]
1067     #[rustfmt::skip]
1068     fn test_trim_multiline_block() {
1069         assert_eq!("\
1070     if x {
1071         y
1072     } else {
1073         z
1074     }", trim_multiline("    if x {
1075             y
1076         } else {
1077             z
1078         }".into(), false));
1079         assert_eq!("\
1080     if x {
1081     \ty
1082     } else {
1083     \tz
1084     }", trim_multiline("    if x {
1085         \ty
1086         } else {
1087         \tz
1088         }".into(), false));
1089     }
1090
1091     #[test]
1092     #[rustfmt::skip]
1093     fn test_trim_multiline_empty_line() {
1094         assert_eq!("\
1095     if x {
1096         y
1097
1098     } else {
1099         z
1100     }", trim_multiline("    if x {
1101             y
1102
1103         } else {
1104             z
1105         }".into(), false));
1106     }
1107
1108     #[test]
1109     fn test_without_block_comments_lines_without_block_comments() {
1110         let result = without_block_comments(vec!["/*", "", "*/"]);
1111         println!("result: {:?}", result);
1112         assert!(result.is_empty());
1113
1114         let result = without_block_comments(vec!["", "/*", "", "*/", "#[crate_type = \"lib\"]", "/*", "", "*/", ""]);
1115         assert_eq!(result, vec!["", "#[crate_type = \"lib\"]", ""]);
1116
1117         let result = without_block_comments(vec!["/* rust", "", "*/"]);
1118         assert!(result.is_empty());
1119
1120         let result = without_block_comments(vec!["/* one-line comment */"]);
1121         assert!(result.is_empty());
1122
1123         let result = without_block_comments(vec!["/* nested", "/* multi-line", "comment", "*/", "test", "*/"]);
1124         assert!(result.is_empty());
1125
1126         let result = without_block_comments(vec!["/* nested /* inline /* comment */ test */ */"]);
1127         assert!(result.is_empty());
1128
1129         let result = without_block_comments(vec!["foo", "bar", "baz"]);
1130         assert_eq!(result, vec!["foo", "bar", "baz"]);
1131     }
1132 }