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