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::*;
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;
20 pub use self::hir::{SpanlessEq, SpanlessHash};
21 pub type MethodArgs = HirVec<P<Expr>>;
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"];
57 /// Produce a nested chain of if-lets and ifs from the patterns:
72 /// if let Some(y) = x {
74 /// if let Some(z) = y {
80 macro_rules! if_let_chain {
81 ([let $pat:pat = $expr:expr, $($tt:tt)+], $block:block) => {
83 if_let_chain!{ [$($tt)+], $block }
86 ([let $pat:pat = $expr:expr], $block:block) => {
91 ([$expr:expr, $($tt:tt)+], $block:block) => {
93 if_let_chain!{ [$($tt)+], $block }
96 ([$expr:expr], $block:block) => {
103 /// Returns true if the two spans come from differing expansions (i.e. one is from a macro and one
105 pub fn differing_macro_contexts(lhs: Span, rhs: Span) -> bool {
106 rhs.expn_id != lhs.expn_id
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())
113 /// Returns true if the macro that expanded the crate was outside of the current crate or was a
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
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"))
133 cx.sess().codemap().with_expn_info(span.expn_id, |info| in_macro_ext(cx, info))
136 /// Check if a `DefId`'s path matches the given absolute type path usage.
140 /// match_def_path(cx, id, &["core", "option", "Option"])
142 pub fn match_def_path(cx: &LateContext, def_id: DefId, path: &[&str]) -> bool {
143 cx.tcx.with_path(def_id, |iter| {
146 iter.inspect(|_| len += 1)
148 .all(|(nm, p)| nm.name().as_str() == *p) && len == path.len()
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 {
155 ty::TyEnum(ref adt, _) | ty::TyStruct(ref adt, _) => match_def_path(cx, adt.did, path),
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);
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)
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);
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)
194 /// Match a `Path` against a slice of segment string literals.
198 /// match_path(path, &["std", "rt", "begin_unwind"])
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)
204 /// Match a `Path` against a slice of segment string literals, e.g.
208 /// match_path(path, &["std", "rt", "begin_unwind"])
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)
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;
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();
226 let segment = match path_it.next() {
227 Some(segment) => segment,
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);
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),
243 items = cstore.item_children(def_id);
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) {
261 cstore::DlDef(def::Def::Trait(trait_id)) => Some(trait_id),
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>>)
271 cx.tcx.populate_implementations_for_trait_if_necessary(trait_id);
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(),
282 traits::SelectionContext::new(&infcx).evaluate_obligation_conservatively(&obligation)
285 /// Match an `Expr` against a chain of methods, and return the matched `Expr`s.
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
306 matched.reverse(); // reverse `matched`, so that it is in the same order as `methods`
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),
322 /// Checks if a `let` decl is from a `for` loop desugaring.
323 pub fn is_from_for_desugar(decl: &Decl) -> bool {
326 let DeclLocal(ref loc) = decl.node,
327 let Some(ref expr) = loc.init,
328 let ExprMatch(_, _, MatchSource::ForLoopDesugar) = expr.node
336 /// Convert a span to a code snippet if available, otherwise use default.
340 /// snippet(cx, expr.span, "..")
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))
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()
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.
357 /// snippet(cx, expr.span, "..")
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)
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))
374 Cow::Owned(format!("{{\n{};\n{}\n}}", code, string))
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, ' ')
385 fn trim_multiline_inner(s: Cow<str>, ignore_first: bool, ch: char) -> Cow<str> {
387 .skip(ignore_first as usize)
392 // ignore empty lines
393 Some(l.char_indices()
394 .find(|&(_, x)| x != ch)
395 .unwrap_or((l.len(), ch))
405 if (ignore_first && i == 0) || l.is_empty() {
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 {
426 map.find(parent_id).and_then(|node| {
427 if let Node::NodeExpr(parent) = node {
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 {
441 Node::NodeBlock(ref block) => Some(block),
442 Node::NodeItem(&Item{ node: ItemFn(_, _, _, _, _, ref block), .. }) => Some(block),
450 pub struct DiagnosticWrapper<'a>(pub DiagnosticBuilder<'a>);
452 impl<'a> Drop for DiagnosticWrapper<'a> {
458 impl<'a> DerefMut for DiagnosticWrapper<'a> {
459 fn deref_mut(&mut self) -> &mut DiagnosticBuilder<'a> {
464 impl<'a> Deref for DiagnosticWrapper<'a> {
465 type Target = DiagnosticBuilder<'a>;
466 fn deref(&self) -> &DiagnosticBuilder<'a> {
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 {
475 &format!("for further information visit https://github.com/Manishearth/rust-clippy/wiki#{}",
478 DiagnosticWrapper(db)
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#{}",
491 DiagnosticWrapper(db)
494 pub fn span_note_and_lint<'a, T: LintContext>(cx: &'a T, lint: &'static Lint, span: Span, msg: &str, note_span: Span,
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);
502 db.span_note(note_span, note);
504 db.fileline_help(span,
505 &format!("for further information visit https://github.com/Manishearth/rust-clippy/wiki#{}",
508 DiagnosticWrapper(db)
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)
515 let mut db = DiagnosticWrapper(cx.struct_span_lint(lint, sp, msg));
516 if cx.current_level(lint) != Level::Allow {
519 &format!("for further information visit https://github.com/Manishearth/rust-clippy/wiki#{}",
525 /// Return the base type for references and raw pointers.
526 pub fn walk_ptrs_ty(ty: ty::Ty) -> ty::Ty {
528 ty::TyRef(_, ref tm) | ty::TyRawPtr(ref tm) => walk_ptrs_ty(tm.ty),
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) {
537 ty::TyRef(_, ref tm) | ty::TyRawPtr(ref tm) => inner(tm.ty, depth + 1),
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 {
555 pub fn is_adjusted(cx: &LateContext, e: &Expr) -> bool {
556 cx.tcx.tables.borrow().adjustments.get(&e.id).is_some()
559 pub struct LimitStack {
563 impl Drop for LimitStack {
565 assert_eq!(self.stack.len(), 1);
570 pub fn new(limit: u64) -> LimitStack {
571 LimitStack { stack: vec![limit] }
573 pub fn limit(&self) -> u64 {
574 *self.stack.last().expect("there should always be a value in the stack")
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));
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)));
586 fn parse_attrs<F: FnMut(u64)>(sess: &Session, attrs: &[ast::Attribute], name: &'static str, mut f: F) {
588 let attr = &attr.node;
589 if attr.is_sugared_doc {
592 if let ast::MetaItemKind::NameValue(ref key, ref value) = attr.value.node {
594 if let LitKind::Str(ref s, _) = value.node {
595 if let Ok(value) = FromStr::from_str(s) {
598 sess.span_err(value.span, "not a number");
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> {
612 let span_name_span = cx.tcx
615 .with_expn_info(span.expn_id, |expn| expn.map(|ei| (ei.callee.name(), ei.call_site)));
617 match span_name_span {
618 Some((mac_name, new_span)) if mac_name.as_str() == name => return Some(new_span),
620 Some((_, new_span)) => span = new_span,
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
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
636 .with_expn_info(span.expn_id, |expn| expn.map(|ei| (ei.callee.name(), ei.call_site)));
638 match span_name_span {
639 Some((mac_name, new_span)) if mac_name.as_str() == name => Some(new_span),
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() {
658 if c.is_lowercase() {
663 } else if c.is_uppercase() {
666 } else if !c.is_lowercase() {
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() {
688 let mut last_i = s.len();
691 if c.is_uppercase() {
694 } else if !c.is_lowercase() {
697 } else if c.is_lowercase() {
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,
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 {
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))
735 Some(unwrap_unstable(expr))
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 })
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 })
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 {
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()