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