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