]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/utils/mod.rs
don't lint on comparing `*const f32`s
[rust.git] / clippy_lints / src / utils / mod.rs
1 use reexport::*;
2 use rustc::hir::*;
3 use rustc::hir::def_id::DefId;
4 use rustc::hir::map::Node;
5 use rustc::lint::{LintContext, LateContext, Level, Lint};
6 use rustc::middle::cstore;
7 use rustc::session::Session;
8 use rustc::traits::ProjectionMode;
9 use rustc::traits;
10 use rustc::ty::subst::Subst;
11 use rustc::ty;
12 use std::borrow::Cow;
13 use std::env;
14 use std::mem;
15 use std::ops::{Deref, DerefMut};
16 use std::str::FromStr;
17 use syntax::ast::{self, LitKind, RangeLimits};
18 use syntax::codemap::{ExpnInfo, Span, ExpnFormat};
19 use syntax::errors::DiagnosticBuilder;
20 use syntax::ptr::P;
21
22 pub mod comparisons;
23 pub mod conf;
24 mod hir;
25 pub mod paths;
26 pub use self::hir::{SpanlessEq, SpanlessHash};
27 pub mod cargo;
28
29 pub type MethodArgs = HirVec<P<Expr>>;
30
31 /// Produce a nested chain of if-lets and ifs from the patterns:
32 ///
33 ///     if_let_chain! {[
34 ///         let Some(y) = x,
35 ///         y.len() == 2,
36 ///         let Some(z) = y,
37 ///     ], {
38 ///         block
39 ///     }}
40 ///
41 /// becomes
42 ///
43 ///     if let Some(y) = x {
44 ///         if y.len() == 2 {
45 ///             if let Some(z) = y {
46 ///                 block
47 ///             }
48 ///         }
49 ///     }
50 #[macro_export]
51 macro_rules! if_let_chain {
52     ([let $pat:pat = $expr:expr, $($tt:tt)+], $block:block) => {
53         if let $pat = $expr {
54            if_let_chain!{ [$($tt)+], $block }
55         }
56     };
57     ([let $pat:pat = $expr:expr], $block:block) => {
58         if let $pat = $expr {
59            $block
60         }
61     };
62     ([let $pat:pat = $expr:expr,], $block:block) => {
63         if let $pat = $expr {
64            $block
65         }
66     };
67     ([$expr:expr, $($tt:tt)+], $block:block) => {
68         if $expr {
69            if_let_chain!{ [$($tt)+], $block }
70         }
71     };
72     ([$expr:expr], $block:block) => {
73         if $expr {
74            $block
75         }
76     };
77     ([$expr:expr,], $block:block) => {
78         if $expr {
79            $block
80         }
81     };
82 }
83
84 /// Returns true if the two spans come from differing expansions (i.e. one is from a macro and one
85 /// isn't).
86 pub fn differing_macro_contexts(lhs: Span, rhs: Span) -> bool {
87     rhs.expn_id != lhs.expn_id
88 }
89 /// Returns true if this `expn_info` was expanded by any macro.
90 pub fn in_macro<T: LintContext>(cx: &T, span: Span) -> bool {
91     cx.sess().codemap().with_expn_info(span.expn_id, |info| info.is_some())
92 }
93
94 /// Returns true if the macro that expanded the crate was outside of the current crate or was a
95 /// compiler plugin.
96 pub fn in_external_macro<T: LintContext>(cx: &T, span: Span) -> bool {
97     /// Invokes `in_macro` with the expansion info of the given span slightly heavy, try to use
98     /// this after other checks have already happened.
99     fn in_macro_ext<T: LintContext>(cx: &T, opt_info: Option<&ExpnInfo>) -> bool {
100         // no ExpnInfo = no macro
101         opt_info.map_or(false, |info| {
102             if let ExpnFormat::MacroAttribute(..) = info.callee.format {
103                 // these are all plugins
104                 return true;
105             }
106             // no span for the callee = external macro
107             info.callee.span.map_or(true, |span| {
108                 // no snippet = external macro or compiler-builtin expansion
109                 cx.sess().codemap().span_to_snippet(span).ok().map_or(true, |code| !code.starts_with("macro_rules"))
110             })
111         })
112     }
113
114     cx.sess().codemap().with_expn_info(span.expn_id, |info| in_macro_ext(cx, info))
115 }
116
117 /// Check if a `DefId`'s path matches the given absolute type path usage.
118 ///
119 /// # Examples
120 /// ```
121 /// match_def_path(cx, id, &["core", "option", "Option"])
122 /// ```
123 ///
124 /// See also the `paths` module.
125 pub fn match_def_path(cx: &LateContext, def_id: DefId, path: &[&str]) -> bool {
126     use syntax::parse::token;
127
128     struct AbsolutePathBuffer {
129         names: Vec<token::InternedString>,
130     }
131
132     impl ty::item_path::ItemPathBuffer for AbsolutePathBuffer {
133         fn root_mode(&self) -> &ty::item_path::RootMode {
134             const ABSOLUTE: &'static ty::item_path::RootMode = &ty::item_path::RootMode::Absolute;
135             ABSOLUTE
136         }
137
138         fn push(&mut self, text: &str) {
139             self.names.push(token::intern(text).as_str());
140         }
141     }
142
143     let mut apb = AbsolutePathBuffer { names: vec![] };
144
145     cx.tcx.push_item_path(&mut apb, def_id);
146
147     apb.names == path
148 }
149
150 /// Check if type is struct or enum type with given def path.
151 pub fn match_type(cx: &LateContext, ty: ty::Ty, path: &[&str]) -> bool {
152     match ty.sty {
153         ty::TyEnum(ref adt, _) |
154         ty::TyStruct(ref adt, _) => match_def_path(cx, adt.did, path),
155         _ => false,
156     }
157 }
158
159 /// Check if the method call given in `expr` belongs to given type.
160 pub fn match_impl_method(cx: &LateContext, expr: &Expr, path: &[&str]) -> bool {
161     let method_call = ty::MethodCall::expr(expr.id);
162
163     let trt_id = cx.tcx
164                    .tables
165                    .borrow()
166                    .method_map
167                    .get(&method_call)
168                    .and_then(|callee| cx.tcx.impl_of_method(callee.def_id));
169     if let Some(trt_id) = trt_id {
170         match_def_path(cx, trt_id, path)
171     } else {
172         false
173     }
174 }
175
176 /// Check if the method call given in `expr` belongs to given trait.
177 pub fn match_trait_method(cx: &LateContext, expr: &Expr, path: &[&str]) -> bool {
178     let method_call = ty::MethodCall::expr(expr.id);
179
180     let trt_id = cx.tcx
181                    .tables
182                    .borrow()
183                    .method_map
184                    .get(&method_call)
185                    .and_then(|callee| cx.tcx.trait_of_item(callee.def_id));
186     if let Some(trt_id) = trt_id {
187         match_def_path(cx, trt_id, path)
188     } else {
189         false
190     }
191 }
192
193 /// Match a `Path` against a slice of segment string literals.
194 ///
195 /// # Examples
196 /// ```
197 /// match_path(path, &["std", "rt", "begin_unwind"])
198 /// ```
199 pub fn match_path(path: &Path, segments: &[&str]) -> bool {
200     path.segments.iter().rev().zip(segments.iter().rev()).all(|(a, b)| a.name.as_str() == *b)
201 }
202
203 /// Match a `Path` against a slice of segment string literals, e.g.
204 ///
205 /// # Examples
206 /// ```
207 /// match_path(path, &["std", "rt", "begin_unwind"])
208 /// ```
209 pub fn match_path_ast(path: &ast::Path, segments: &[&str]) -> bool {
210     path.segments.iter().rev().zip(segments.iter().rev()).all(|(a, b)| a.identifier.name.as_str() == *b)
211 }
212
213 /// Get the definition associated to a path.
214 /// TODO: investigate if there is something more efficient for that.
215 pub fn path_to_def(cx: &LateContext, path: &[&str]) -> Option<cstore::DefLike> {
216     let cstore = &cx.tcx.sess.cstore;
217
218     let crates = cstore.crates();
219     let krate = crates.iter().find(|&&krate| cstore.crate_name(krate) == path[0]);
220     if let Some(krate) = krate {
221         let mut items = cstore.crate_top_level_items(*krate);
222         let mut path_it = path.iter().skip(1).peekable();
223
224         loop {
225             let segment = match path_it.next() {
226                 Some(segment) => segment,
227                 None => return None,
228             };
229
230             for item in &mem::replace(&mut items, vec![]) {
231                 if item.name.as_str() == *segment {
232                     if path_it.peek().is_none() {
233                         return Some(item.def);
234                     }
235
236                     let def_id = match item.def {
237                         cstore::DefLike::DlDef(def) => def.def_id(),
238                         cstore::DefLike::DlImpl(def_id) => def_id,
239                         _ => panic!("Unexpected {:?}", item.def),
240                     };
241
242                     items = cstore.item_children(def_id);
243                     break;
244                 }
245             }
246         }
247     } else {
248         None
249     }
250 }
251
252 /// Convenience function to get the `DefId` of a trait by path.
253 pub fn get_trait_def_id(cx: &LateContext, path: &[&str]) -> Option<DefId> {
254     let def = match path_to_def(cx, path) {
255         Some(def) => def,
256         None => return None,
257     };
258
259     match def {
260         cstore::DlDef(def::Def::Trait(trait_id)) => Some(trait_id),
261         _ => None,
262     }
263 }
264
265 /// Check whether a type implements a trait.
266 /// See also `get_trait_def_id`.
267 pub fn implements_trait<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, ty: ty::Ty<'tcx>, trait_id: DefId,
268                                   ty_params: Vec<ty::Ty<'tcx>>)
269                                   -> bool {
270     cx.tcx.populate_implementations_for_trait_if_necessary(trait_id);
271
272     let ty = cx.tcx.erase_regions(&ty);
273     cx.tcx.infer_ctxt(None, None, ProjectionMode::Any).enter(|infcx| {
274         let obligation = cx.tcx.predicate_for_trait_def(traits::ObligationCause::dummy(),
275                                                         trait_id,
276                                                         0,
277                                                         ty,
278                                                         ty_params);
279
280         traits::SelectionContext::new(&infcx).evaluate_obligation_conservatively(&obligation)
281     })
282 }
283
284 /// Match an `Expr` against a chain of methods, and return the matched `Expr`s.
285 ///
286 /// For example, if `expr` represents the `.baz()` in `foo.bar().baz()`,
287 /// `matched_method_chain(expr, &["bar", "baz"])` will return a `Vec` containing the `Expr`s for
288 /// `.bar()` and `.baz()`
289 pub fn method_chain_args<'a>(expr: &'a Expr, methods: &[&str]) -> Option<Vec<&'a MethodArgs>> {
290     let mut current = expr;
291     let mut matched = Vec::with_capacity(methods.len());
292     for method_name in methods.iter().rev() {
293         // method chains are stored last -> first
294         if let ExprMethodCall(ref name, _, ref args) = current.node {
295             if name.node.as_str() == *method_name {
296                 matched.push(args); // build up `matched` backwards
297                 current = &args[0] // go to parent expression
298             } else {
299                 return None;
300             }
301         } else {
302             return None;
303         }
304     }
305     matched.reverse(); // reverse `matched`, so that it is in the same order as `methods`
306     Some(matched)
307 }
308
309
310 /// Get the name of the item the expression is in, if available.
311 pub fn get_item_name(cx: &LateContext, expr: &Expr) -> Option<Name> {
312     let parent_id = cx.tcx.map.get_parent(expr.id);
313     match cx.tcx.map.find(parent_id) {
314         Some(Node::NodeItem(&Item { ref name, .. })) |
315         Some(Node::NodeTraitItem(&TraitItem { ref name, .. })) |
316         Some(Node::NodeImplItem(&ImplItem { ref name, .. })) => Some(*name),
317         _ => None,
318     }
319 }
320
321 /// Checks if a `let` decl is from a `for` loop desugaring.
322 pub fn is_from_for_desugar(decl: &Decl) -> bool {
323     if_let_chain! {[
324         let DeclLocal(ref loc) = decl.node,
325         let Some(ref expr) = loc.init,
326         let ExprMatch(_, _, MatchSource::ForLoopDesugar) = expr.node
327     ], {
328         return true;
329     }}
330     false
331 }
332
333
334 /// Convert a span to a code snippet if available, otherwise use default.
335 ///
336 /// # Example
337 /// ```
338 /// snippet(cx, expr.span, "..")
339 /// ```
340 pub fn snippet<'a, T: LintContext>(cx: &T, span: Span, default: &'a str) -> Cow<'a, str> {
341     cx.sess().codemap().span_to_snippet(span).map(From::from).unwrap_or_else(|_| Cow::Borrowed(default))
342 }
343
344 /// Convert a span to a code snippet. Returns `None` if not available.
345 pub fn snippet_opt<T: LintContext>(cx: &T, span: Span) -> Option<String> {
346     cx.sess().codemap().span_to_snippet(span).ok()
347 }
348
349 /// Convert a span (from a block) to a code snippet if available, otherwise use default.
350 /// This trims the code of indentation, except for the first line. Use it for blocks or block-like
351 /// things which need to be printed as such.
352 ///
353 /// # Example
354 /// ```
355 /// snippet(cx, expr.span, "..")
356 /// ```
357 pub fn snippet_block<'a, T: LintContext>(cx: &T, span: Span, default: &'a str) -> Cow<'a, str> {
358     let snip = snippet(cx, span, default);
359     trim_multiline(snip, true)
360 }
361
362 /// Like `snippet_block`, but add braces if the expr is not an `ExprBlock`.
363 /// Also takes an `Option<String>` which can be put inside the braces.
364 pub fn expr_block<'a, T: LintContext>(cx: &T, expr: &Expr, option: Option<String>, default: &'a str) -> Cow<'a, str> {
365     let code = snippet_block(cx, expr.span, default);
366     let string = option.unwrap_or_default();
367     if let ExprBlock(_) = expr.node {
368         Cow::Owned(format!("{}{}", code, string))
369     } else if string.is_empty() {
370         Cow::Owned(format!("{{ {} }}", code))
371     } else {
372         Cow::Owned(format!("{{\n{};\n{}\n}}", code, string))
373     }
374 }
375
376 /// Trim indentation from a multiline string with possibility of ignoring the first line.
377 pub fn trim_multiline(s: Cow<str>, ignore_first: bool) -> Cow<str> {
378     let s_space = trim_multiline_inner(s, ignore_first, ' ');
379     let s_tab = trim_multiline_inner(s_space, ignore_first, '\t');
380     trim_multiline_inner(s_tab, ignore_first, ' ')
381 }
382
383 fn trim_multiline_inner(s: Cow<str>, ignore_first: bool, ch: char) -> Cow<str> {
384     let x = s.lines()
385              .skip(ignore_first as usize)
386              .filter_map(|l| {
387                  if l.is_empty() {
388                      None
389                  } else {
390                      // ignore empty lines
391                      Some(l.char_indices()
392                            .find(|&(_, x)| x != ch)
393                            .unwrap_or((l.len(), ch))
394                            .0)
395                  }
396              })
397              .min()
398              .unwrap_or(0);
399     if x > 0 {
400         Cow::Owned(s.lines()
401                     .enumerate()
402                     .map(|(i, l)| {
403                         if (ignore_first && i == 0) || l.is_empty() {
404                             l
405                         } else {
406                             l.split_at(x).1
407                         }
408                     })
409                     .collect::<Vec<_>>()
410                     .join("\n"))
411     } else {
412         s
413     }
414 }
415
416 /// Get a parent expressions if any â€“ this is useful to constrain a lint.
417 pub fn get_parent_expr<'c>(cx: &'c LateContext, e: &Expr) -> Option<&'c Expr> {
418     let map = &cx.tcx.map;
419     let node_id: NodeId = e.id;
420     let parent_id: NodeId = map.get_parent_node(node_id);
421     if node_id == parent_id {
422         return None;
423     }
424     map.find(parent_id).and_then(|node| {
425         if let Node::NodeExpr(parent) = node {
426             Some(parent)
427         } else {
428             None
429         }
430     })
431 }
432
433 pub fn get_enclosing_block<'c>(cx: &'c LateContext, node: NodeId) -> Option<&'c Block> {
434     let map = &cx.tcx.map;
435     let enclosing_node = map.get_enclosing_scope(node)
436                             .and_then(|enclosing_id| map.find(enclosing_id));
437     if let Some(node) = enclosing_node {
438         match node {
439             Node::NodeBlock(ref block) => Some(block),
440             Node::NodeItem(&Item { node: ItemFn(_, _, _, _, _, ref block), .. }) => Some(block),
441             _ => None,
442         }
443     } else {
444         None
445     }
446 }
447
448 pub struct DiagnosticWrapper<'a>(pub DiagnosticBuilder<'a>);
449
450 impl<'a> Drop for DiagnosticWrapper<'a> {
451     fn drop(&mut self) {
452         self.0.emit();
453     }
454 }
455
456 impl<'a> DerefMut for DiagnosticWrapper<'a> {
457     fn deref_mut(&mut self) -> &mut DiagnosticBuilder<'a> {
458         &mut self.0
459     }
460 }
461
462 impl<'a> Deref for DiagnosticWrapper<'a> {
463     type Target = DiagnosticBuilder<'a>;
464     fn deref(&self) -> &DiagnosticBuilder<'a> {
465         &self.0
466     }
467 }
468
469 impl<'a> DiagnosticWrapper<'a> {
470     fn wiki_link(&mut self, lint: &'static Lint) {
471         if env::var("CLIPPY_DISABLE_WIKI_LINKS").is_err() {
472             self.help(&format!("for further information visit https://github.com/Manishearth/rust-clippy/wiki#{}",
473                                lint.name_lower()));
474         }
475     }
476 }
477
478 pub fn span_lint<'a, T: LintContext>(cx: &'a T, lint: &'static Lint, sp: Span, msg: &str) -> DiagnosticWrapper<'a> {
479     let mut db = DiagnosticWrapper(cx.struct_span_lint(lint, sp, msg));
480     if cx.current_level(lint) != Level::Allow {
481         db.wiki_link(lint);
482     }
483     db
484 }
485
486 pub fn span_help_and_lint<'a, T: LintContext>(cx: &'a T, lint: &'static Lint, span: Span, msg: &str, help: &str)
487                                               -> DiagnosticWrapper<'a> {
488     let mut db = DiagnosticWrapper(cx.struct_span_lint(lint, span, msg));
489     if cx.current_level(lint) != Level::Allow {
490         db.help(help);
491         db.wiki_link(lint);
492     }
493     db
494 }
495
496 pub fn span_note_and_lint<'a, T: LintContext>(cx: &'a T, lint: &'static Lint, span: Span, msg: &str, note_span: Span,
497                                               note: &str)
498                                               -> DiagnosticWrapper<'a> {
499     let mut db = DiagnosticWrapper(cx.struct_span_lint(lint, span, msg));
500     if cx.current_level(lint) != Level::Allow {
501         if note_span == span {
502             db.note(note);
503         } else {
504             db.span_note(note_span, note);
505         }
506         db.wiki_link(lint);
507     }
508     db
509 }
510
511 pub fn span_lint_and_then<'a, T: LintContext, F>(cx: &'a T, lint: &'static Lint, sp: Span, msg: &str, f: F)
512                                                  -> DiagnosticWrapper<'a>
513     where F: FnOnce(&mut DiagnosticWrapper)
514 {
515     let mut db = DiagnosticWrapper(cx.struct_span_lint(lint, sp, msg));
516     if cx.current_level(lint) != Level::Allow {
517         f(&mut db);
518         db.wiki_link(lint);
519     }
520     db
521 }
522
523 /// Return the base type for references and raw pointers.
524 pub fn walk_ptrs_ty(ty: ty::Ty) -> ty::Ty {
525     match ty.sty {
526         ty::TyRef(_, ref tm) => walk_ptrs_ty(tm.ty),
527         _ => ty,
528     }
529 }
530
531 /// Return the base type for references and raw pointers, and count reference depth.
532 pub fn walk_ptrs_ty_depth(ty: ty::Ty) -> (ty::Ty, usize) {
533     fn inner(ty: ty::Ty, depth: usize) -> (ty::Ty, usize) {
534         match ty.sty {
535             ty::TyRef(_, ref tm) => inner(tm.ty, depth + 1),
536             _ => (ty, depth),
537         }
538     }
539     inner(ty, 0)
540 }
541
542 /// Check whether the given expression is a constant literal of the given value.
543 pub fn is_integer_literal(expr: &Expr, value: u64) -> bool {
544     // FIXME: use constant folding
545     if let ExprLit(ref spanned) = expr.node {
546         if let LitKind::Int(v, _) = spanned.node {
547             return v == value;
548         }
549     }
550     false
551 }
552
553 pub fn is_adjusted(cx: &LateContext, e: &Expr) -> bool {
554     cx.tcx.tables.borrow().adjustments.get(&e.id).is_some()
555 }
556
557 pub struct LimitStack {
558     stack: Vec<u64>,
559 }
560
561 impl Drop for LimitStack {
562     fn drop(&mut self) {
563         assert_eq!(self.stack.len(), 1);
564     }
565 }
566
567 impl LimitStack {
568     pub fn new(limit: u64) -> LimitStack {
569         LimitStack { stack: vec![limit] }
570     }
571     pub fn limit(&self) -> u64 {
572         *self.stack.last().expect("there should always be a value in the stack")
573     }
574     pub fn push_attrs(&mut self, sess: &Session, attrs: &[ast::Attribute], name: &'static str) {
575         let stack = &mut self.stack;
576         parse_attrs(sess, attrs, name, |val| stack.push(val));
577     }
578     pub fn pop_attrs(&mut self, sess: &Session, attrs: &[ast::Attribute], name: &'static str) {
579         let stack = &mut self.stack;
580         parse_attrs(sess, attrs, name, |val| assert_eq!(stack.pop(), Some(val)));
581     }
582 }
583
584 fn parse_attrs<F: FnMut(u64)>(sess: &Session, attrs: &[ast::Attribute], name: &'static str, mut f: F) {
585     for attr in attrs {
586         let attr = &attr.node;
587         if attr.is_sugared_doc {
588             continue;
589         }
590         if let ast::MetaItemKind::NameValue(ref key, ref value) = attr.value.node {
591             if *key == name {
592                 if let LitKind::Str(ref s, _) = value.node {
593                     if let Ok(value) = FromStr::from_str(s) {
594                         f(value)
595                     } else {
596                         sess.span_err(value.span, "not a number");
597                     }
598                 } else {
599                     unreachable!()
600                 }
601             }
602         }
603     }
604 }
605
606 /// Return the pre-expansion span if is this comes from an expansion of the macro `name`.
607 /// See also `is_direct_expn_of`.
608 pub fn is_expn_of(cx: &LateContext, mut span: Span, name: &str) -> Option<Span> {
609     loop {
610         let span_name_span = cx.tcx
611                                .sess
612                                .codemap()
613                                .with_expn_info(span.expn_id, |expn| expn.map(|ei| (ei.callee.name(), ei.call_site)));
614
615         match span_name_span {
616             Some((mac_name, new_span)) if mac_name.as_str() == name => return Some(new_span),
617             None => return None,
618             Some((_, new_span)) => span = new_span,
619         }
620     }
621 }
622
623 /// Return the pre-expansion span if is this directly comes from an expansion of the macro `name`.
624 /// The difference with `is_expn_of` is that in
625 /// ```rust,ignore
626 /// foo!(bar!(42));
627 /// ```
628 /// `42` is considered expanded from `foo!` and `bar!` by `is_expn_of` but only `bar!` by
629 /// `is_direct_expn_of`.
630 pub fn is_direct_expn_of(cx: &LateContext, span: Span, name: &str) -> Option<Span> {
631     let span_name_span = cx.tcx
632                            .sess
633                            .codemap()
634                            .with_expn_info(span.expn_id, |expn| expn.map(|ei| (ei.callee.name(), ei.call_site)));
635
636     match span_name_span {
637         Some((mac_name, new_span)) if mac_name.as_str() == name => Some(new_span),
638         _ => None,
639     }
640 }
641
642 /// Return the index of the character after the first camel-case component of `s`.
643 pub fn camel_case_until(s: &str) -> usize {
644     let mut iter = s.char_indices();
645     if let Some((_, first)) = iter.next() {
646         if !first.is_uppercase() {
647             return 0;
648         }
649     } else {
650         return 0;
651     }
652     let mut up = true;
653     let mut last_i = 0;
654     for (i, c) in iter {
655         if up {
656             if c.is_lowercase() {
657                 up = false;
658             } else {
659                 return last_i;
660             }
661         } else if c.is_uppercase() {
662             up = true;
663             last_i = i;
664         } else if !c.is_lowercase() {
665             return i;
666         }
667     }
668     if up {
669         last_i
670     } else {
671         s.len()
672     }
673 }
674
675 /// Return index of the last camel-case component of `s`.
676 pub fn camel_case_from(s: &str) -> usize {
677     let mut iter = s.char_indices().rev();
678     if let Some((_, first)) = iter.next() {
679         if !first.is_lowercase() {
680             return s.len();
681         }
682     } else {
683         return s.len();
684     }
685     let mut down = true;
686     let mut last_i = s.len();
687     for (i, c) in iter {
688         if down {
689             if c.is_uppercase() {
690                 down = false;
691                 last_i = i;
692             } else if !c.is_lowercase() {
693                 return last_i;
694             }
695         } else if c.is_lowercase() {
696             down = true;
697         } else {
698             return last_i;
699         }
700     }
701     last_i
702 }
703
704 /// Represent a range akin to `ast::ExprKind::Range`.
705 #[derive(Debug, Copy, Clone)]
706 pub struct UnsugaredRange<'a> {
707     pub start: Option<&'a Expr>,
708     pub end: Option<&'a Expr>,
709     pub limits: RangeLimits,
710 }
711
712 /// Unsugar a `hir` range.
713 pub fn unsugar_range(expr: &Expr) -> Option<UnsugaredRange> {
714     // To be removed when ranges get stable.
715     fn unwrap_unstable(expr: &Expr) -> &Expr {
716         if let ExprBlock(ref block) = expr.node {
717             if block.rules == BlockCheckMode::PushUnstableBlock || block.rules == BlockCheckMode::PopUnstableBlock {
718                 if let Some(ref expr) = block.expr {
719                     return expr;
720                 }
721             }
722         }
723
724         expr
725     }
726
727     fn get_field<'a>(name: &str, fields: &'a [Field]) -> Option<&'a Expr> {
728         let expr = &fields.iter()
729                           .find(|field| field.name.node.as_str() == name)
730                           .unwrap_or_else(|| panic!("missing {} field for range", name))
731                           .expr;
732
733         Some(unwrap_unstable(expr))
734     }
735
736     // The range syntax is expanded to literal paths starting with `core` or `std` depending on
737     // `#[no_std]`. Testing both instead of resolving the paths.
738
739     match unwrap_unstable(expr).node {
740         ExprPath(None, ref path) => {
741             if match_path(path, &paths::RANGE_FULL_STD) || match_path(path, &paths::RANGE_FULL) {
742                 Some(UnsugaredRange {
743                     start: None,
744                     end: None,
745                     limits: RangeLimits::HalfOpen,
746                 })
747             } else {
748                 None
749             }
750         }
751         ExprStruct(ref path, ref fields, None) => {
752             if match_path(path, &paths::RANGE_FROM_STD) || match_path(path, &paths::RANGE_FROM) {
753                 Some(UnsugaredRange {
754                     start: get_field("start", fields),
755                     end: None,
756                     limits: RangeLimits::HalfOpen,
757                 })
758             } else if match_path(path, &paths::RANGE_INCLUSIVE_NON_EMPTY_STD) ||
759                match_path(path, &paths::RANGE_INCLUSIVE_NON_EMPTY) {
760                 Some(UnsugaredRange {
761                     start: get_field("start", fields),
762                     end: get_field("end", fields),
763                     limits: RangeLimits::Closed,
764                 })
765             } else if match_path(path, &paths::RANGE_STD) || match_path(path, &paths::RANGE) {
766                 Some(UnsugaredRange {
767                     start: get_field("start", fields),
768                     end: get_field("end", fields),
769                     limits: RangeLimits::HalfOpen,
770                 })
771             } else if match_path(path, &paths::RANGE_TO_INCLUSIVE_STD) || match_path(path, &paths::RANGE_TO_INCLUSIVE) {
772                 Some(UnsugaredRange {
773                     start: None,
774                     end: get_field("end", fields),
775                     limits: RangeLimits::Closed,
776                 })
777             } else if match_path(path, &paths::RANGE_TO_STD) || match_path(path, &paths::RANGE_TO) {
778                 Some(UnsugaredRange {
779                     start: None,
780                     end: get_field("end", fields),
781                     limits: RangeLimits::HalfOpen,
782                 })
783             } else {
784                 None
785             }
786         }
787         _ => None,
788     }
789 }
790
791 /// Convenience function to get the return type of a function or `None` if the function diverges.
792 pub fn return_ty<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, fn_item: NodeId) -> Option<ty::Ty<'tcx>> {
793     let parameter_env = ty::ParameterEnvironment::for_item(cx.tcx, fn_item);
794     let fn_sig = cx.tcx.node_id_to_type(fn_item).fn_sig().subst(cx.tcx, parameter_env.free_substs);
795     let fn_sig = cx.tcx.liberate_late_bound_regions(parameter_env.free_id_outlive, &fn_sig);
796     if let ty::FnConverging(ret_ty) = fn_sig.output {
797         Some(ret_ty)
798     } else {
799         None
800     }
801 }
802
803 /// Check if two types are the same.
804 // FIXME: this works correctly for lifetimes bounds (`for <'a> Foo<'a>` == `for <'b> Foo<'b>` but
805 // not for type parameters.
806 pub fn same_tys<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, a: ty::Ty<'tcx>, b: ty::Ty<'tcx>, parameter_item: NodeId) -> bool {
807     let parameter_env = ty::ParameterEnvironment::for_item(cx.tcx, parameter_item);
808     cx.tcx.infer_ctxt(None, Some(parameter_env), ProjectionMode::Any).enter(|infcx| {
809         let new_a = a.subst(infcx.tcx, infcx.parameter_environment.free_substs);
810         let new_b = b.subst(infcx.tcx, infcx.parameter_environment.free_substs);
811         infcx.can_equate(&new_a, &new_b).is_ok()
812     })
813 }
814
815 /// Recover the essential nodes of a desugared for loop:
816 /// `for pat in arg { body }` becomes `(pat, arg, body)`.
817 pub fn recover_for_loop(expr: &Expr) -> Option<(&Pat, &Expr, &Expr)> {
818     if_let_chain! {[
819         let ExprMatch(ref iterexpr, ref arms, _) = expr.node,
820         let ExprCall(_, ref iterargs) = iterexpr.node,
821         iterargs.len() == 1 && arms.len() == 1 && arms[0].guard.is_none(),
822         let ExprLoop(ref block, _) = arms[0].body.node,
823         block.stmts.is_empty(),
824         let Some(ref loopexpr) = block.expr,
825         let ExprMatch(_, ref innerarms, MatchSource::ForLoopDesugar) = loopexpr.node,
826         innerarms.len() == 2 && innerarms[0].pats.len() == 1,
827         let PatKind::TupleStruct(_, ref somepats, _) = innerarms[0].pats[0].node,
828         somepats.len() == 1
829     ], {
830         return Some((&somepats[0],
831                      &iterargs[0],
832                      &innerarms[0].body));
833     }}
834     None
835 }