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