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