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