]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/utils/mod.rs
Introduce `multispan_sugg`
[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 rustc_errors;
13 use std::borrow::Cow;
14 use std::env;
15 use std::mem;
16 use std::str::FromStr;
17 use syntax::ast::{self, LitKind};
18 use syntax::codemap::{ExpnFormat, ExpnInfo, MultiSpan, Span};
19 use syntax::errors::DiagnosticBuilder;
20 use syntax::ptr::P;
21
22 pub mod cargo;
23 pub mod comparisons;
24 pub mod conf;
25 mod hir;
26 pub mod paths;
27 pub mod sugg;
28 pub use self::hir::{SpanlessEq, SpanlessHash};
29
30 pub type MethodArgs = HirVec<P<Expr>>;
31
32 /// Produce a nested chain of if-lets and ifs from the patterns:
33 ///
34 ///     if_let_chain! {[
35 ///         let Some(y) = x,
36 ///         y.len() == 2,
37 ///         let Some(z) = y,
38 ///     ], {
39 ///         block
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 pub mod higher;
86
87 /// Returns true if the two spans come from differing expansions (i.e. one is from a macro and one
88 /// isn't).
89 pub fn differing_macro_contexts(lhs: Span, rhs: Span) -> bool {
90     rhs.expn_id != lhs.expn_id
91 }
92 /// Returns true if this `expn_info` was expanded by any macro.
93 pub fn in_macro<T: LintContext>(cx: &T, span: Span) -> bool {
94     cx.sess().codemap().with_expn_info(span.expn_id, |info| info.is_some())
95 }
96
97 /// Returns true if the macro that expanded the crate was outside of the current crate or was a
98 /// compiler plugin.
99 pub fn in_external_macro<T: LintContext>(cx: &T, span: Span) -> bool {
100     /// Invokes `in_macro` with the expansion info of the given span slightly heavy, try to use
101     /// this after other checks have already happened.
102     fn in_macro_ext<T: LintContext>(cx: &T, opt_info: Option<&ExpnInfo>) -> bool {
103         // no ExpnInfo = no macro
104         opt_info.map_or(false, |info| {
105             if let ExpnFormat::MacroAttribute(..) = info.callee.format {
106                 // these are all plugins
107                 return true;
108             }
109             // no span for the callee = external macro
110             info.callee.span.map_or(true, |span| {
111                 // no snippet = external macro or compiler-builtin expansion
112                 cx.sess().codemap().span_to_snippet(span).ok().map_or(true, |code| !code.starts_with("macro_rules"))
113             })
114         })
115     }
116
117     cx.sess().codemap().with_expn_info(span.expn_id, |info| in_macro_ext(cx, info))
118 }
119
120 /// Check if a `DefId`'s path matches the given absolute type path usage.
121 ///
122 /// # Examples
123 /// ```
124 /// match_def_path(cx, id, &["core", "option", "Option"])
125 /// ```
126 ///
127 /// See also the `paths` module.
128 pub fn match_def_path(cx: &LateContext, def_id: DefId, path: &[&str]) -> bool {
129     use syntax::parse::token;
130
131     struct AbsolutePathBuffer {
132         names: Vec<token::InternedString>,
133     }
134
135     impl ty::item_path::ItemPathBuffer for AbsolutePathBuffer {
136         fn root_mode(&self) -> &ty::item_path::RootMode {
137             const ABSOLUTE: &'static ty::item_path::RootMode = &ty::item_path::RootMode::Absolute;
138             ABSOLUTE
139         }
140
141         fn push(&mut self, text: &str) {
142             self.names.push(token::intern(text).as_str());
143         }
144     }
145
146     let mut apb = AbsolutePathBuffer { names: vec![] };
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 /// Convert a span to a code snippet if available, otherwise use default.
325 ///
326 /// # Example
327 /// ```
328 /// snippet(cx, expr.span, "..")
329 /// ```
330 pub fn snippet<'a, T: LintContext>(cx: &T, span: Span, default: &'a str) -> Cow<'a, str> {
331     cx.sess().codemap().span_to_snippet(span).map(From::from).unwrap_or_else(|_| Cow::Borrowed(default))
332 }
333
334 /// Convert a span to a code snippet. Returns `None` if not available.
335 pub fn snippet_opt<T: LintContext>(cx: &T, span: Span) -> Option<String> {
336     cx.sess().codemap().span_to_snippet(span).ok()
337 }
338
339 /// Convert a span (from a block) to a code snippet if available, otherwise use default.
340 /// This trims the code of indentation, except for the first line. Use it for blocks or block-like
341 /// things which need to be printed as such.
342 ///
343 /// # Example
344 /// ```
345 /// snippet(cx, expr.span, "..")
346 /// ```
347 pub fn snippet_block<'a, T: LintContext>(cx: &T, span: Span, default: &'a str) -> Cow<'a, str> {
348     let snip = snippet(cx, span, default);
349     trim_multiline(snip, true)
350 }
351
352 /// Like `snippet_block`, but add braces if the expr is not an `ExprBlock`.
353 /// Also takes an `Option<String>` which can be put inside the braces.
354 pub fn expr_block<'a, T: LintContext>(cx: &T, expr: &Expr, option: Option<String>, default: &'a str) -> Cow<'a, str> {
355     let code = snippet_block(cx, expr.span, default);
356     let string = option.unwrap_or_default();
357     if let ExprBlock(_) = expr.node {
358         Cow::Owned(format!("{}{}", code, string))
359     } else if string.is_empty() {
360         Cow::Owned(format!("{{ {} }}", code))
361     } else {
362         Cow::Owned(format!("{{\n{};\n{}\n}}", code, string))
363     }
364 }
365
366 /// Trim indentation from a multiline string with possibility of ignoring the first line.
367 pub fn trim_multiline(s: Cow<str>, ignore_first: bool) -> Cow<str> {
368     let s_space = trim_multiline_inner(s, ignore_first, ' ');
369     let s_tab = trim_multiline_inner(s_space, ignore_first, '\t');
370     trim_multiline_inner(s_tab, ignore_first, ' ')
371 }
372
373 fn trim_multiline_inner(s: Cow<str>, ignore_first: bool, ch: char) -> Cow<str> {
374     let x = s.lines()
375              .skip(ignore_first as usize)
376              .filter_map(|l| {
377                  if l.is_empty() {
378                      None
379                  } else {
380                      // ignore empty lines
381                      Some(l.char_indices()
382                            .find(|&(_, x)| x != ch)
383                            .unwrap_or((l.len(), ch))
384                            .0)
385                  }
386              })
387              .min()
388              .unwrap_or(0);
389     if x > 0 {
390         Cow::Owned(s.lines()
391                     .enumerate()
392                     .map(|(i, l)| {
393                         if (ignore_first && i == 0) || l.is_empty() {
394                             l
395                         } else {
396                             l.split_at(x).1
397                         }
398                     })
399                     .collect::<Vec<_>>()
400                     .join("\n"))
401     } else {
402         s
403     }
404 }
405
406 /// Get a parent expressions if any – this is useful to constrain a lint.
407 pub fn get_parent_expr<'c>(cx: &'c LateContext, e: &Expr) -> Option<&'c Expr> {
408     let map = &cx.tcx.map;
409     let node_id: NodeId = e.id;
410     let parent_id: NodeId = map.get_parent_node(node_id);
411     if node_id == parent_id {
412         return None;
413     }
414     map.find(parent_id).and_then(|node| {
415         if let Node::NodeExpr(parent) = node {
416             Some(parent)
417         } else {
418             None
419         }
420     })
421 }
422
423 pub fn get_enclosing_block<'c>(cx: &'c LateContext, node: NodeId) -> Option<&'c Block> {
424     let map = &cx.tcx.map;
425     let enclosing_node = map.get_enclosing_scope(node)
426                             .and_then(|enclosing_id| map.find(enclosing_id));
427     if let Some(node) = enclosing_node {
428         match node {
429             Node::NodeBlock(ref block) => Some(block),
430             Node::NodeItem(&Item { node: ItemFn(_, _, _, _, _, ref block), .. }) => Some(block),
431             _ => None,
432         }
433     } else {
434         None
435     }
436 }
437
438 pub struct DiagnosticWrapper<'a>(pub DiagnosticBuilder<'a>);
439
440 impl<'a> Drop for DiagnosticWrapper<'a> {
441     fn drop(&mut self) {
442         self.0.emit();
443     }
444 }
445
446 impl<'a> DiagnosticWrapper<'a> {
447     fn wiki_link(&mut self, lint: &'static Lint) {
448         if env::var("CLIPPY_DISABLE_WIKI_LINKS").is_err() {
449             self.0.help(&format!("for further information visit https://github.com/Manishearth/rust-clippy/wiki#{}",
450                                lint.name_lower()));
451         }
452     }
453 }
454
455 pub fn span_lint<T: LintContext>(cx: &T, lint: &'static Lint, sp: Span, msg: &str) {
456     let mut db = DiagnosticWrapper(cx.struct_span_lint(lint, sp, msg));
457     if cx.current_level(lint) != Level::Allow {
458         db.wiki_link(lint);
459     }
460 }
461
462 // FIXME: needless lifetime doesn't trigger here
463 pub fn span_help_and_lint<'a, T: LintContext>(cx: &'a T, lint: &'static Lint, span: Span, msg: &str, help: &str) {
464     let mut db = DiagnosticWrapper(cx.struct_span_lint(lint, span, msg));
465     if cx.current_level(lint) != Level::Allow {
466         db.0.help(help);
467         db.wiki_link(lint);
468     }
469 }
470
471 pub fn span_note_and_lint<'a, T: LintContext>(cx: &'a T, lint: &'static Lint, span: Span, msg: &str, note_span: Span,
472                                               note: &str) {
473     let mut db = DiagnosticWrapper(cx.struct_span_lint(lint, span, msg));
474     if cx.current_level(lint) != Level::Allow {
475         if note_span == span {
476             db.0.note(note);
477         } else {
478             db.0.span_note(note_span, note);
479         }
480         db.wiki_link(lint);
481     }
482 }
483
484 pub fn span_lint_and_then<'a, T: LintContext, F>(cx: &'a T, lint: &'static Lint, sp: Span, msg: &str, f: F)
485     where F: FnOnce(&mut DiagnosticBuilder<'a>)
486 {
487     let mut db = DiagnosticWrapper(cx.struct_span_lint(lint, sp, msg));
488     if cx.current_level(lint) != Level::Allow {
489         f(&mut db.0);
490         db.wiki_link(lint);
491     }
492 }
493
494 /// Create a suggestion made from several `span → replacement`.
495 ///
496 /// Note: in the JSON format (used by `compiletest_rs`), the help message will appear once per
497 /// replacement. In human-readable format though, it only appears once before the whole suggestion.
498 pub fn multispan_sugg(db: &mut DiagnosticBuilder, help_msg: String, sugg: &[(Span, &str)]) {
499     let sugg = rustc_errors::RenderSpan::Suggestion(rustc_errors::CodeSuggestion {
500         msp: MultiSpan::from_spans(sugg.iter().map(|&(span, _)| span).collect()),
501         substitutes: sugg.iter().map(|&(_, subs)| subs.to_owned()).collect(),
502     });
503
504     let sub = rustc_errors::SubDiagnostic {
505         level: rustc_errors::Level::Help,
506         message: help_msg,
507         span: MultiSpan::new(),
508         render_span: Some(sugg),
509     };
510     db.children.push(sub);
511 }
512
513 /// Return the base type for references and raw pointers.
514 pub fn walk_ptrs_ty(ty: ty::Ty) -> ty::Ty {
515     match ty.sty {
516         ty::TyRef(_, ref tm) => walk_ptrs_ty(tm.ty),
517         _ => ty,
518     }
519 }
520
521 /// Return the base type for references and raw pointers, and count reference depth.
522 pub fn walk_ptrs_ty_depth(ty: ty::Ty) -> (ty::Ty, usize) {
523     fn inner(ty: ty::Ty, depth: usize) -> (ty::Ty, usize) {
524         match ty.sty {
525             ty::TyRef(_, ref tm) => inner(tm.ty, depth + 1),
526             _ => (ty, depth),
527         }
528     }
529     inner(ty, 0)
530 }
531
532 /// Check whether the given expression is a constant literal of the given value.
533 pub fn is_integer_literal(expr: &Expr, value: u64) -> bool {
534     // FIXME: use constant folding
535     if let ExprLit(ref spanned) = expr.node {
536         if let LitKind::Int(v, _) = spanned.node {
537             return v == value;
538         }
539     }
540     false
541 }
542
543 pub fn is_adjusted(cx: &LateContext, e: &Expr) -> bool {
544     cx.tcx.tables.borrow().adjustments.get(&e.id).is_some()
545 }
546
547 pub struct LimitStack {
548     stack: Vec<u64>,
549 }
550
551 impl Drop for LimitStack {
552     fn drop(&mut self) {
553         assert_eq!(self.stack.len(), 1);
554     }
555 }
556
557 impl LimitStack {
558     pub fn new(limit: u64) -> LimitStack {
559         LimitStack { stack: vec![limit] }
560     }
561     pub fn limit(&self) -> u64 {
562         *self.stack.last().expect("there should always be a value in the stack")
563     }
564     pub fn push_attrs(&mut self, sess: &Session, attrs: &[ast::Attribute], name: &'static str) {
565         let stack = &mut self.stack;
566         parse_attrs(sess, attrs, name, |val| stack.push(val));
567     }
568     pub fn pop_attrs(&mut self, sess: &Session, attrs: &[ast::Attribute], name: &'static str) {
569         let stack = &mut self.stack;
570         parse_attrs(sess, attrs, name, |val| assert_eq!(stack.pop(), Some(val)));
571     }
572 }
573
574 fn parse_attrs<F: FnMut(u64)>(sess: &Session, attrs: &[ast::Attribute], name: &'static str, mut f: F) {
575     for attr in attrs {
576         let attr = &attr.node;
577         if attr.is_sugared_doc {
578             continue;
579         }
580         if let ast::MetaItemKind::NameValue(ref key, ref value) = attr.value.node {
581             if *key == name {
582                 if let LitKind::Str(ref s, _) = value.node {
583                     if let Ok(value) = FromStr::from_str(s) {
584                         f(value)
585                     } else {
586                         sess.span_err(value.span, "not a number");
587                     }
588                 } else {
589                     unreachable!()
590                 }
591             }
592         }
593     }
594 }
595
596 /// Return the pre-expansion span if is this comes from an expansion of the macro `name`.
597 /// See also `is_direct_expn_of`.
598 pub fn is_expn_of(cx: &LateContext, mut span: Span, name: &str) -> Option<Span> {
599     loop {
600         let span_name_span = cx.tcx
601                                .sess
602                                .codemap()
603                                .with_expn_info(span.expn_id, |expn| expn.map(|ei| (ei.callee.name(), ei.call_site)));
604
605         match span_name_span {
606             Some((mac_name, new_span)) if mac_name.as_str() == name => return Some(new_span),
607             None => return None,
608             Some((_, new_span)) => span = new_span,
609         }
610     }
611 }
612
613 /// Return the pre-expansion span if is this directly comes from an expansion of the macro `name`.
614 /// The difference with `is_expn_of` is that in
615 /// ```rust,ignore
616 /// foo!(bar!(42));
617 /// ```
618 /// `42` is considered expanded from `foo!` and `bar!` by `is_expn_of` but only `bar!` by
619 /// `is_direct_expn_of`.
620 pub fn is_direct_expn_of(cx: &LateContext, span: Span, name: &str) -> Option<Span> {
621     let span_name_span = cx.tcx
622                            .sess
623                            .codemap()
624                            .with_expn_info(span.expn_id, |expn| expn.map(|ei| (ei.callee.name(), ei.call_site)));
625
626     match span_name_span {
627         Some((mac_name, new_span)) if mac_name.as_str() == name => Some(new_span),
628         _ => None,
629     }
630 }
631
632 /// Return the index of the character after the first camel-case component of `s`.
633 pub fn camel_case_until(s: &str) -> usize {
634     let mut iter = s.char_indices();
635     if let Some((_, first)) = iter.next() {
636         if !first.is_uppercase() {
637             return 0;
638         }
639     } else {
640         return 0;
641     }
642     let mut up = true;
643     let mut last_i = 0;
644     for (i, c) in iter {
645         if up {
646             if c.is_lowercase() {
647                 up = false;
648             } else {
649                 return last_i;
650             }
651         } else if c.is_uppercase() {
652             up = true;
653             last_i = i;
654         } else if !c.is_lowercase() {
655             return i;
656         }
657     }
658     if up {
659         last_i
660     } else {
661         s.len()
662     }
663 }
664
665 /// Return index of the last camel-case component of `s`.
666 pub fn camel_case_from(s: &str) -> usize {
667     let mut iter = s.char_indices().rev();
668     if let Some((_, first)) = iter.next() {
669         if !first.is_lowercase() {
670             return s.len();
671         }
672     } else {
673         return s.len();
674     }
675     let mut down = true;
676     let mut last_i = s.len();
677     for (i, c) in iter {
678         if down {
679             if c.is_uppercase() {
680                 down = false;
681                 last_i = i;
682             } else if !c.is_lowercase() {
683                 return last_i;
684             }
685         } else if c.is_lowercase() {
686             down = true;
687         } else {
688             return last_i;
689         }
690     }
691     last_i
692 }
693
694 /// Convenience function to get the return type of a function or `None` if the function diverges.
695 pub fn return_ty<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, fn_item: NodeId) -> Option<ty::Ty<'tcx>> {
696     let parameter_env = ty::ParameterEnvironment::for_item(cx.tcx, fn_item);
697     let fn_sig = cx.tcx.node_id_to_type(fn_item).fn_sig().subst(cx.tcx, parameter_env.free_substs);
698     let fn_sig = cx.tcx.liberate_late_bound_regions(parameter_env.free_id_outlive, &fn_sig);
699     if let ty::FnConverging(ret_ty) = fn_sig.output {
700         Some(ret_ty)
701     } else {
702         None
703     }
704 }
705
706 /// Check if two types are the same.
707 // FIXME: this works correctly for lifetimes bounds (`for <'a> Foo<'a>` == `for <'b> Foo<'b>` but
708 // not for type parameters.
709 pub fn same_tys<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, a: ty::Ty<'tcx>, b: ty::Ty<'tcx>, parameter_item: NodeId) -> bool {
710     let parameter_env = ty::ParameterEnvironment::for_item(cx.tcx, parameter_item);
711     cx.tcx.infer_ctxt(None, Some(parameter_env), ProjectionMode::Any).enter(|infcx| {
712         let new_a = a.subst(infcx.tcx, infcx.parameter_environment.free_substs);
713         let new_b = b.subst(infcx.tcx, infcx.parameter_environment.free_substs);
714         infcx.can_equate(&new_a, &new_b).is_ok()
715     })
716 }