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