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