]> git.lizzy.rs Git - rust.git/blob - src/utils/mod.rs
Merge pull request #727 from oli-obk/similar_names
[rust.git] / src / utils / mod.rs
1 use reexport::*;
2 use rustc::front::map::Node;
3 use rustc::lint::{LintContext, LateContext, Level, Lint};
4 use rustc::middle::def_id::DefId;
5 use rustc::middle::traits::ProjectionMode;
6 use rustc::middle::{cstore, def, infer, ty, traits};
7 use rustc::session::Session;
8 use rustc_front::hir::*;
9 use std::borrow::Cow;
10 use std::mem;
11 use std::ops::{Deref, DerefMut};
12 use std::str::FromStr;
13 use syntax::ast::{self, LitKind, RangeLimits};
14 use syntax::codemap::{ExpnInfo, Span, ExpnFormat};
15 use syntax::errors::DiagnosticBuilder;
16 use syntax::ptr::P;
17
18 pub mod conf;
19 mod hir;
20 pub use self::hir::{SpanlessEq, SpanlessHash};
21 pub type MethodArgs = HirVec<P<Expr>>;
22
23 // module DefPaths for certain structs/enums we check for
24 pub const BEGIN_UNWIND: [&'static str; 3] = ["std", "rt", "begin_unwind"];
25 pub const BOX_NEW_PATH: [&'static str; 4] = ["std", "boxed", "Box", "new"];
26 pub const BTREEMAP_ENTRY_PATH: [&'static str; 4] = ["collections", "btree", "map", "Entry"];
27 pub const BTREEMAP_PATH: [&'static str; 4] = ["collections", "btree", "map", "BTreeMap"];
28 pub const CLONE_PATH: [&'static str; 3] = ["clone", "Clone", "clone"];
29 pub const CLONE_TRAIT_PATH: [&'static str; 2] = ["clone", "Clone"];
30 pub const COW_PATH: [&'static str; 3] = ["collections", "borrow", "Cow"];
31 pub const DEBUG_FMT_METHOD_PATH: [&'static str; 4] = ["std", "fmt", "Debug", "fmt"];
32 pub const DEFAULT_TRAIT_PATH: [&'static str; 3] = ["core", "default", "Default"];
33 pub const DISPLAY_FMT_METHOD_PATH: [&'static str; 4] = ["std", "fmt", "Display", "fmt"];
34 pub const DROP_PATH: [&'static str; 3] = ["core", "mem", "drop"];
35 pub const FMT_ARGUMENTS_NEWV1_PATH: [&'static str; 4] = ["std", "fmt", "Arguments", "new_v1"];
36 pub const FMT_ARGUMENTV1_NEW_PATH: [&'static str; 4] = ["std", "fmt", "ArgumentV1", "new"];
37 pub const HASHMAP_ENTRY_PATH: [&'static str; 5] = ["std", "collections", "hash", "map", "Entry"];
38 pub const HASHMAP_PATH: [&'static str; 5] = ["std", "collections", "hash", "map", "HashMap"];
39 pub const HASH_PATH: [&'static str; 2] = ["hash", "Hash"];
40 pub const IO_PRINT_PATH: [&'static str; 3] = ["std", "io", "_print"];
41 pub const LL_PATH: [&'static str; 3] = ["collections", "linked_list", "LinkedList"];
42 pub const MUTEX_PATH: [&'static str; 4] = ["std", "sync", "mutex", "Mutex"];
43 pub const OPEN_OPTIONS_PATH: [&'static str; 3] = ["std", "fs", "OpenOptions"];
44 pub const OPTION_PATH: [&'static str; 3] = ["core", "option", "Option"];
45 pub const RANGE_FROM_PATH: [&'static str; 3] = ["std", "ops", "RangeFrom"];
46 pub const RANGE_FULL_PATH: [&'static str; 3] = ["std", "ops", "RangeFull"];
47 pub const RANGE_INCLUSIVE_NON_EMPTY_PATH: [&'static str; 4] = ["std", "ops", "RangeInclusive", "NonEmpty"];
48 pub const RANGE_PATH: [&'static str; 3] = ["std", "ops", "Range"];
49 pub const RANGE_TO_INCLUSIVE_PATH: [&'static str; 3] = ["std", "ops", "RangeToInclusive"];
50 pub const RANGE_TO_PATH: [&'static str; 3] = ["std", "ops", "RangeTo"];
51 pub const REGEX_NEW_PATH: [&'static str; 3] = ["regex", "Regex", "new"];
52 pub const RESULT_PATH: [&'static str; 3] = ["core", "result", "Result"];
53 pub const STRING_PATH: [&'static str; 3] = ["collections", "string", "String"];
54 pub const VEC_FROM_ELEM_PATH: [&'static str; 3] = ["std", "vec", "from_elem"];
55 pub const VEC_PATH: [&'static str; 3] = ["collections", "vec", "Vec"];
56
57 /// Produce a nested chain of if-lets and ifs from the patterns:
58 ///
59 ///     if_let_chain! {
60 ///         [
61 ///             let Some(y) = x,
62 ///             y.len() == 2,
63 ///             let Some(z) = y,
64 ///         ],
65 ///         {
66 ///             block
67 ///         }
68 ///     }
69 ///
70 /// becomes
71 ///
72 ///     if let Some(y) = x {
73 ///         if y.len() == 2 {
74 ///             if let Some(z) = y {
75 ///                 block
76 ///             }
77 ///         }
78 ///     }
79 #[macro_export]
80 macro_rules! if_let_chain {
81     ([let $pat:pat = $expr:expr, $($tt:tt)+], $block:block) => {
82         if let $pat = $expr {
83            if_let_chain!{ [$($tt)+], $block }
84         }
85     };
86     ([let $pat:pat = $expr:expr], $block:block) => {
87         if let $pat = $expr {
88            $block
89         }
90     };
91     ([$expr:expr, $($tt:tt)+], $block:block) => {
92         if $expr {
93            if_let_chain!{ [$($tt)+], $block }
94         }
95     };
96     ([$expr:expr], $block:block) => {
97         if $expr {
98            $block
99         }
100     };
101 }
102
103 /// Returns true if the two spans come from differing expansions (i.e. one is from a macro and one
104 /// isn't).
105 pub fn differing_macro_contexts(lhs: Span, rhs: Span) -> bool {
106     rhs.expn_id != lhs.expn_id
107 }
108 /// Returns true if this `expn_info` was expanded by any macro.
109 pub fn in_macro<T: LintContext>(cx: &T, span: Span) -> bool {
110     cx.sess().codemap().with_expn_info(span.expn_id, |info| info.is_some())
111 }
112
113 /// Returns true if the macro that expanded the crate was outside of the current crate or was a
114 /// compiler plugin.
115 pub fn in_external_macro<T: LintContext>(cx: &T, span: Span) -> bool {
116     /// Invokes in_macro with the expansion info of the given span slightly heavy, try to use this
117     /// after other checks have already happened.
118     fn in_macro_ext<T: LintContext>(cx: &T, opt_info: Option<&ExpnInfo>) -> bool {
119         // no ExpnInfo = no macro
120         opt_info.map_or(false, |info| {
121             if let ExpnFormat::MacroAttribute(..) = info.callee.format {
122                 // these are all plugins
123                 return true;
124             }
125             // no span for the callee = external macro
126             info.callee.span.map_or(true, |span| {
127                 // no snippet = external macro or compiler-builtin expansion
128                 cx.sess().codemap().span_to_snippet(span).ok().map_or(true, |code| !code.starts_with("macro_rules"))
129             })
130         })
131     }
132
133     cx.sess().codemap().with_expn_info(span.expn_id, |info| in_macro_ext(cx, info))
134 }
135
136 /// Check if a `DefId`'s path matches the given absolute type path usage.
137 ///
138 /// # Examples
139 /// ```
140 /// match_def_path(cx, id, &["core", "option", "Option"])
141 /// ```
142 pub fn match_def_path(cx: &LateContext, def_id: DefId, path: &[&str]) -> bool {
143     cx.tcx.with_path(def_id, |iter| {
144         let mut len = 0;
145
146         iter.inspect(|_| len += 1)
147             .zip(path)
148             .all(|(nm, p)| nm.name().as_str() == *p) && len == path.len()
149     })
150 }
151
152 /// Check if type is struct or enum type with given def path.
153 pub fn match_type(cx: &LateContext, ty: ty::Ty, path: &[&str]) -> bool {
154     match ty.sty {
155         ty::TyEnum(ref adt, _) | 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.identifier.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     let infcx = infer::new_infer_ctxt(cx.tcx, &cx.tcx.tables, None, ProjectionMode::Any);
275     let obligation = traits::predicate_for_trait_def(cx.tcx,
276                                                      traits::ObligationCause::dummy(),
277                                                      trait_id,
278                                                      0,
279                                                      ty,
280                                                      ty_params);
281
282     traits::SelectionContext::new(&infcx).evaluate_obligation_conservatively(&obligation)
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         [
326             let DeclLocal(ref loc) = decl.node,
327             let Some(ref expr) = loc.init,
328             let ExprMatch(_, _, MatchSource::ForLoopDesugar) = expr.node
329         ],
330         { return true; }
331     };
332     false
333 }
334
335
336 /// Convert a span to a code snippet if available, otherwise use default.
337 ///
338 /// # Example
339 /// ```
340 /// snippet(cx, expr.span, "..")
341 /// ```
342 pub fn snippet<'a, T: LintContext>(cx: &T, span: Span, default: &'a str) -> Cow<'a, str> {
343     cx.sess().codemap().span_to_snippet(span).map(From::from).unwrap_or_else(|_| Cow::Borrowed(default))
344 }
345
346 /// Convert a span to a code snippet. Returns `None` if not available.
347 pub fn snippet_opt<T: LintContext>(cx: &T, span: Span) -> Option<String> {
348     cx.sess().codemap().span_to_snippet(span).ok()
349 }
350
351 /// Convert a span (from a block) to a code snippet if available, otherwise use default.
352 /// This trims the code of indentation, except for the first line. Use it for blocks or block-like
353 /// things which need to be printed as such.
354 ///
355 /// # Example
356 /// ```
357 /// snippet(cx, expr.span, "..")
358 /// ```
359 pub fn snippet_block<'a, T: LintContext>(cx: &T, span: Span, default: &'a str) -> Cow<'a, str> {
360     let snip = snippet(cx, span, default);
361     trim_multiline(snip, true)
362 }
363
364 /// Like `snippet_block`, but add braces if the expr is not an `ExprBlock`.
365 /// Also takes an `Option<String>` which can be put inside the braces.
366 pub fn expr_block<'a, T: LintContext>(cx: &T, expr: &Expr, option: Option<String>, default: &'a str) -> Cow<'a, str> {
367     let code = snippet_block(cx, expr.span, default);
368     let string = option.unwrap_or_default();
369     if let ExprBlock(_) = expr.node {
370         Cow::Owned(format!("{}{}", code, string))
371     } else if string.is_empty() {
372         Cow::Owned(format!("{{ {} }}", code))
373     } else {
374         Cow::Owned(format!("{{\n{};\n{}\n}}", code, string))
375     }
376 }
377
378 /// Trim indentation from a multiline string with possibility of ignoring the first line.
379 pub fn trim_multiline(s: Cow<str>, ignore_first: bool) -> Cow<str> {
380     let s_space = trim_multiline_inner(s, ignore_first, ' ');
381     let s_tab = trim_multiline_inner(s_space, ignore_first, '\t');
382     trim_multiline_inner(s_tab, ignore_first, ' ')
383 }
384
385 fn trim_multiline_inner(s: Cow<str>, ignore_first: bool, ch: char) -> Cow<str> {
386     let x = s.lines()
387              .skip(ignore_first as usize)
388              .filter_map(|l| {
389                  if l.is_empty() {
390                      None
391                  } else {
392                      // ignore empty lines
393                      Some(l.char_indices()
394                            .find(|&(_, x)| x != ch)
395                            .unwrap_or((l.len(), ch))
396                            .0)
397                  }
398              })
399              .min()
400              .unwrap_or(0);
401     if x > 0 {
402         Cow::Owned(s.lines()
403                     .enumerate()
404                     .map(|(i, l)| {
405                         if (ignore_first && i == 0) || l.is_empty() {
406                             l
407                         } else {
408                             l.split_at(x).1
409                         }
410                     })
411                     .collect::<Vec<_>>()
412                     .join("\n"))
413     } else {
414         s
415     }
416 }
417
418 /// Get a parent expressions if any â€“ this is useful to constrain a lint.
419 pub fn get_parent_expr<'c>(cx: &'c LateContext, e: &Expr) -> Option<&'c Expr> {
420     let map = &cx.tcx.map;
421     let node_id: NodeId = e.id;
422     let parent_id: NodeId = map.get_parent_node(node_id);
423     if node_id == parent_id {
424         return None;
425     }
426     map.find(parent_id).and_then(|node| {
427         if let Node::NodeExpr(parent) = node {
428             Some(parent)
429         } else {
430             None
431         }
432     })
433 }
434
435 pub fn get_enclosing_block<'c>(cx: &'c LateContext, node: NodeId) -> Option<&'c Block> {
436     let map = &cx.tcx.map;
437     let enclosing_node = map.get_enclosing_scope(node)
438                             .and_then(|enclosing_id| map.find(enclosing_id));
439     if let Some(node) = enclosing_node {
440         match node {
441             Node::NodeBlock(ref block) => Some(block),
442             Node::NodeItem(&Item{ node: ItemFn(_, _, _, _, _, ref block), .. }) => Some(block),
443             _ => None,
444         }
445     } else {
446         None
447     }
448 }
449
450 pub struct DiagnosticWrapper<'a>(pub DiagnosticBuilder<'a>);
451
452 impl<'a> Drop for DiagnosticWrapper<'a> {
453     fn drop(&mut self) {
454         self.0.emit();
455     }
456 }
457
458 impl<'a> DerefMut for DiagnosticWrapper<'a> {
459     fn deref_mut(&mut self) -> &mut DiagnosticBuilder<'a> {
460         &mut self.0
461     }
462 }
463
464 impl<'a> Deref for DiagnosticWrapper<'a> {
465     type Target = DiagnosticBuilder<'a>;
466     fn deref(&self) -> &DiagnosticBuilder<'a> {
467         &self.0
468     }
469 }
470
471 pub fn span_lint<'a, T: LintContext>(cx: &'a T, lint: &'static Lint, sp: Span, msg: &str) -> DiagnosticWrapper<'a> {
472     let mut db = cx.struct_span_lint(lint, sp, msg);
473     if cx.current_level(lint) != Level::Allow {
474         db.fileline_help(sp,
475                          &format!("for further information visit https://github.com/Manishearth/rust-clippy/wiki#{}",
476                                   lint.name_lower()));
477     }
478     DiagnosticWrapper(db)
479 }
480
481 pub fn span_help_and_lint<'a, T: LintContext>(cx: &'a T, lint: &'static Lint, span: Span, msg: &str, help: &str)
482                                               -> DiagnosticWrapper<'a> {
483     let mut db = cx.struct_span_lint(lint, span, msg);
484     if cx.current_level(lint) != Level::Allow {
485         db.fileline_help(span,
486                          &format!("{}\nfor further information visit \
487                                    https://github.com/Manishearth/rust-clippy/wiki#{}",
488                                   help,
489                                   lint.name_lower()));
490     }
491     DiagnosticWrapper(db)
492 }
493
494 pub fn span_note_and_lint<'a, T: LintContext>(cx: &'a T, lint: &'static Lint, span: Span, msg: &str, note_span: Span,
495                                               note: &str)
496                                               -> DiagnosticWrapper<'a> {
497     let mut db = cx.struct_span_lint(lint, span, msg);
498     if cx.current_level(lint) != Level::Allow {
499         if note_span == span {
500             db.fileline_note(note_span, note);
501         } else {
502             db.span_note(note_span, note);
503         }
504         db.fileline_help(span,
505                          &format!("for further information visit https://github.com/Manishearth/rust-clippy/wiki#{}",
506                                   lint.name_lower()));
507     }
508     DiagnosticWrapper(db)
509 }
510
511 pub fn span_lint_and_then<'a, T: LintContext, F>(cx: &'a T, lint: &'static Lint, sp: Span, msg: &str, f: F)
512                                                  -> DiagnosticWrapper<'a>
513     where F: FnOnce(&mut DiagnosticWrapper)
514 {
515     let mut db = DiagnosticWrapper(cx.struct_span_lint(lint, sp, msg));
516     if cx.current_level(lint) != Level::Allow {
517         f(&mut db);
518         db.fileline_help(sp,
519                          &format!("for further information visit https://github.com/Manishearth/rust-clippy/wiki#{}",
520                                   lint.name_lower()));
521     }
522     db
523 }
524
525 /// Return the base type for references and raw pointers.
526 pub fn walk_ptrs_ty(ty: ty::Ty) -> ty::Ty {
527     match ty.sty {
528         ty::TyRef(_, ref tm) | ty::TyRawPtr(ref tm) => walk_ptrs_ty(tm.ty),
529         _ => ty,
530     }
531 }
532
533 /// Return the base type for references and raw pointers, and count reference depth.
534 pub fn walk_ptrs_ty_depth(ty: ty::Ty) -> (ty::Ty, usize) {
535     fn inner(ty: ty::Ty, depth: usize) -> (ty::Ty, usize) {
536         match ty.sty {
537             ty::TyRef(_, ref tm) | ty::TyRawPtr(ref tm) => inner(tm.ty, depth + 1),
538             _ => (ty, depth),
539         }
540     }
541     inner(ty, 0)
542 }
543
544 /// Check whether the given expression is a constant literal of the given value.
545 pub fn is_integer_literal(expr: &Expr, value: u64) -> bool {
546     // FIXME: use constant folding
547     if let ExprLit(ref spanned) = expr.node {
548         if let LitKind::Int(v, _) = spanned.node {
549             return v == value;
550         }
551     }
552     false
553 }
554
555 pub fn is_adjusted(cx: &LateContext, e: &Expr) -> bool {
556     cx.tcx.tables.borrow().adjustments.get(&e.id).is_some()
557 }
558
559 pub struct LimitStack {
560     stack: Vec<u64>,
561 }
562
563 impl Drop for LimitStack {
564     fn drop(&mut self) {
565         assert_eq!(self.stack.len(), 1);
566     }
567 }
568
569 impl LimitStack {
570     pub fn new(limit: u64) -> LimitStack {
571         LimitStack { stack: vec![limit] }
572     }
573     pub fn limit(&self) -> u64 {
574         *self.stack.last().expect("there should always be a value in the stack")
575     }
576     pub fn push_attrs(&mut self, sess: &Session, attrs: &[ast::Attribute], name: &'static str) {
577         let stack = &mut self.stack;
578         parse_attrs(sess, attrs, name, |val| stack.push(val));
579     }
580     pub fn pop_attrs(&mut self, sess: &Session, attrs: &[ast::Attribute], name: &'static str) {
581         let stack = &mut self.stack;
582         parse_attrs(sess, attrs, name, |val| assert_eq!(stack.pop(), Some(val)));
583     }
584 }
585
586 fn parse_attrs<F: FnMut(u64)>(sess: &Session, attrs: &[ast::Attribute], name: &'static str, mut f: F) {
587     for attr in attrs {
588         let attr = &attr.node;
589         if attr.is_sugared_doc {
590             continue;
591         }
592         if let ast::MetaItemKind::NameValue(ref key, ref value) = attr.value.node {
593             if *key == name {
594                 if let LitKind::Str(ref s, _) = value.node {
595                     if let Ok(value) = FromStr::from_str(s) {
596                         f(value)
597                     } else {
598                         sess.span_err(value.span, "not a number");
599                     }
600                 } else {
601                     unreachable!()
602                 }
603             }
604         }
605     }
606 }
607
608 /// Return the pre-expansion span if is this comes from an expansion of the macro `name`.
609 /// See also `is_direct_expn_of`.
610 pub fn is_expn_of(cx: &LateContext, mut span: Span, name: &str) -> Option<Span> {
611     loop {
612         let span_name_span = cx.tcx
613                                .sess
614                                .codemap()
615                                .with_expn_info(span.expn_id, |expn| expn.map(|ei| (ei.callee.name(), ei.call_site)));
616
617         match span_name_span {
618             Some((mac_name, new_span)) if mac_name.as_str() == name => return Some(new_span),
619             None => return None,
620             Some((_, new_span)) => span = new_span,
621         }
622     }
623 }
624
625 /// Return the pre-expansion span if is this directly comes from an expansion of the macro `name`.
626 /// The difference with `is_expn_of` is that in
627 /// ```rust,ignore
628 /// foo!(bar!(42));
629 /// ```
630 /// `42` is considered expanded from `foo!` and `bar!` by `is_expn_of` but only `bar!` by
631 /// `is_direct_expn_of`.
632 pub fn is_direct_expn_of(cx: &LateContext, span: Span, name: &str) -> Option<Span> {
633     let span_name_span = cx.tcx
634                            .sess
635                            .codemap()
636                            .with_expn_info(span.expn_id, |expn| expn.map(|ei| (ei.callee.name(), ei.call_site)));
637
638     match span_name_span {
639         Some((mac_name, new_span)) if mac_name.as_str() == name => Some(new_span),
640         _ => None,
641     }
642 }
643
644 /// Returns index of character after first CamelCase component of `s`
645 pub fn camel_case_until(s: &str) -> usize {
646     let mut iter = s.char_indices();
647     if let Some((_, first)) = iter.next() {
648         if !first.is_uppercase() {
649             return 0;
650         }
651     } else {
652         return 0;
653     }
654     let mut up = true;
655     let mut last_i = 0;
656     for (i, c) in iter {
657         if up {
658             if c.is_lowercase() {
659                 up = false;
660             } else {
661                 return last_i;
662             }
663         } else if c.is_uppercase() {
664             up = true;
665             last_i = i;
666         } else if !c.is_lowercase() {
667             return i;
668         }
669     }
670     if up {
671         last_i
672     } else {
673         s.len()
674     }
675 }
676
677 /// Returns index of last CamelCase component of `s`.
678 pub fn camel_case_from(s: &str) -> usize {
679     let mut iter = s.char_indices().rev();
680     if let Some((_, first)) = iter.next() {
681         if !first.is_lowercase() {
682             return s.len();
683         }
684     } else {
685         return s.len();
686     }
687     let mut down = true;
688     let mut last_i = s.len();
689     for (i, c) in iter {
690         if down {
691             if c.is_uppercase() {
692                 down = false;
693                 last_i = i;
694             } else if !c.is_lowercase() {
695                 return last_i;
696             }
697         } else if c.is_lowercase() {
698             down = true;
699         } else {
700             return last_i;
701         }
702     }
703     last_i
704 }
705
706 /// Represents a range akin to `ast::ExprKind::Range`.
707 #[derive(Debug, Copy, Clone)]
708 pub struct UnsugaredRange<'a> {
709     pub start: Option<&'a Expr>,
710     pub end: Option<&'a Expr>,
711     pub limits: RangeLimits,
712 }
713
714 /// Unsugar a `hir` range.
715 pub fn unsugar_range(expr: &Expr) -> Option<UnsugaredRange> {
716     // To be removed when ranges get stable.
717     fn unwrap_unstable(expr: &Expr) -> &Expr {
718         if let ExprBlock(ref block) = expr.node {
719             if block.rules == BlockCheckMode::PushUnstableBlock || block.rules == BlockCheckMode::PopUnstableBlock {
720                 if let Some(ref expr) = block.expr {
721                     return expr;
722                 }
723             }
724         }
725
726         expr
727     }
728
729     fn get_field<'a>(name: &str, fields: &'a [Field]) -> Option<&'a Expr> {
730         let expr = &fields.iter()
731                           .find(|field| field.name.node.as_str() == name)
732                           .unwrap_or_else(|| panic!("missing {} field for range", name))
733                           .expr;
734
735         Some(unwrap_unstable(expr))
736     }
737
738     match unwrap_unstable(&expr).node {
739         ExprPath(None, ref path) => {
740             if match_path(path, &RANGE_FULL_PATH) {
741                 Some(UnsugaredRange { start: None, end: None, limits: RangeLimits::HalfOpen })
742             } else {
743                 None
744             }
745         }
746         ExprStruct(ref path, ref fields, None) => {
747             if match_path(path, &RANGE_FROM_PATH) {
748                 Some(UnsugaredRange { start: get_field("start", fields), end: None, limits: RangeLimits::HalfOpen })
749             } else if match_path(path, &RANGE_INCLUSIVE_NON_EMPTY_PATH) {
750                 Some(UnsugaredRange { start: get_field("start", fields), end: get_field("end", fields), limits: RangeLimits::Closed })
751             } else if match_path(path, &RANGE_PATH) {
752                 Some(UnsugaredRange { start: get_field("start", fields), end: get_field("end", fields), limits: RangeLimits::HalfOpen })
753             } else if match_path(path, &RANGE_TO_INCLUSIVE_PATH) {
754                 Some(UnsugaredRange { start: None, end: get_field("end", fields), limits: RangeLimits::Closed })
755             } else if match_path(path, &RANGE_TO_PATH) {
756                 Some(UnsugaredRange { start: None, end: get_field("end", fields), limits: RangeLimits::HalfOpen })
757             } else {
758                 None
759             }
760         }
761         _ => None,
762     }
763 }
764
765 /// Convenience function to get the return type of a function or `None` if the function diverges.
766 pub fn return_ty(fun: ty::Ty) -> Option<ty::Ty> {
767     if let ty::FnConverging(ret_ty) = fun.fn_sig().skip_binder().output {
768         Some(ret_ty)
769     } else {
770         None
771     }
772 }
773
774 /// Check if two types are the same.
775 // FIXME: this works correctly for lifetimes bounds (`for <'a> Foo<'a>` == `for <'b> Foo<'b>` but
776 // not for type parameters.
777 pub fn same_tys<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, a: ty::Ty<'tcx>, b: ty::Ty<'tcx>) -> bool {
778     let infcx = infer::new_infer_ctxt(cx.tcx, &cx.tcx.tables, None, ProjectionMode::Any);
779     infcx.can_equate(&cx.tcx.erase_regions(&a), &cx.tcx.erase_regions(&b)).is_ok()
780 }