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