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