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;
10 use rustc::ty::subst::Subst;
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;
26 pub use self::hir::{SpanlessEq, SpanlessHash};
29 pub type MethodArgs = HirVec<P<Expr>>;
31 /// Produce a nested chain of if-lets and ifs from the patterns:
46 /// if let Some(y) = x {
48 /// if let Some(z) = y {
54 macro_rules! if_let_chain {
55 ([let $pat:pat = $expr:expr, $($tt:tt)+], $block:block) => {
57 if_let_chain!{ [$($tt)+], $block }
60 ([let $pat:pat = $expr:expr], $block:block) => {
65 ([let $pat:pat = $expr:expr,], $block:block) => {
70 ([$expr:expr, $($tt:tt)+], $block:block) => {
72 if_let_chain!{ [$($tt)+], $block }
75 ([$expr:expr], $block:block) => {
80 ([$expr:expr,], $block:block) => {
87 /// Returns true if the two spans come from differing expansions (i.e. one is from a macro and one
89 pub fn differing_macro_contexts(lhs: Span, rhs: Span) -> bool {
90 rhs.expn_id != lhs.expn_id
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())
97 /// Returns true if the macro that expanded the crate was outside of the current crate or was a
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
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"))
117 cx.sess().codemap().with_expn_info(span.expn_id, |info| in_macro_ext(cx, info))
120 /// Check if a `DefId`'s path matches the given absolute type path usage.
124 /// match_def_path(cx, id, &["core", "option", "Option"])
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;
131 struct AbsolutePathBuffer {
132 names: Vec<token::InternedString>,
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;
141 fn push(&mut self, text: &str) {
142 self.names.push(token::intern(text).as_str());
146 let mut apb = AbsolutePathBuffer {
150 cx.tcx.push_item_path(&mut apb, def_id);
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 {
158 ty::TyEnum(ref adt, _) |
159 ty::TyStruct(ref adt, _) => match_def_path(cx, adt.did, path),
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);
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)
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);
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)
198 /// Match a `Path` against a slice of segment string literals.
202 /// match_path(path, &["std", "rt", "begin_unwind"])
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)
208 /// Match a `Path` against a slice of segment string literals, e.g.
212 /// match_path(path, &["std", "rt", "begin_unwind"])
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)
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;
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();
230 let segment = match path_it.next() {
231 Some(segment) => segment,
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);
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),
247 items = cstore.item_children(def_id);
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) {
265 cstore::DlDef(def::Def::Trait(trait_id)) => Some(trait_id),
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>>)
275 cx.tcx.populate_implementations_for_trait_if_necessary(trait_id);
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(),
285 traits::SelectionContext::new(&infcx).evaluate_obligation_conservatively(&obligation)
289 /// Match an `Expr` against a chain of methods, and return the matched `Expr`s.
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
310 matched.reverse(); // reverse `matched`, so that it is in the same order as `methods`
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),
326 /// Checks if a `let` decl is from a `for` loop desugaring.
327 pub fn is_from_for_desugar(decl: &Decl) -> bool {
330 let DeclLocal(ref loc) = decl.node,
331 let Some(ref expr) = loc.init,
332 let ExprMatch(_, _, MatchSource::ForLoopDesugar) = expr.node
340 /// Convert a span to a code snippet if available, otherwise use default.
344 /// snippet(cx, expr.span, "..")
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))
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()
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.
361 /// snippet(cx, expr.span, "..")
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)
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))
378 Cow::Owned(format!("{{\n{};\n{}\n}}", code, string))
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, ' ')
389 fn trim_multiline_inner(s: Cow<str>, ignore_first: bool, ch: char) -> Cow<str> {
391 .skip(ignore_first as usize)
396 // ignore empty lines
397 Some(l.char_indices()
398 .find(|&(_, x)| x != ch)
399 .unwrap_or((l.len(), ch))
409 if (ignore_first && i == 0) || l.is_empty() {
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 {
430 map.find(parent_id).and_then(|node| {
431 if let Node::NodeExpr(parent) = node {
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 {
445 Node::NodeBlock(ref block) => Some(block),
446 Node::NodeItem(&Item { node: ItemFn(_, _, _, _, _, ref block), .. }) => Some(block),
454 pub struct DiagnosticWrapper<'a>(pub DiagnosticBuilder<'a>);
456 impl<'a> Drop for DiagnosticWrapper<'a> {
462 impl<'a> DerefMut for DiagnosticWrapper<'a> {
463 fn deref_mut(&mut self) -> &mut DiagnosticBuilder<'a> {
468 impl<'a> Deref for DiagnosticWrapper<'a> {
469 type Target = DiagnosticBuilder<'a>;
470 fn deref(&self) -> &DiagnosticBuilder<'a> {
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#{}",
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 {
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 {
502 pub fn span_note_and_lint<'a, T: LintContext>(cx: &'a T, lint: &'static Lint, span: Span, msg: &str, note_span: Span,
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 {
510 db.span_note(note_span, note);
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)
521 let mut db = DiagnosticWrapper(cx.struct_span_lint(lint, sp, msg));
522 if cx.current_level(lint) != Level::Allow {
529 /// Return the base type for references and raw pointers.
530 pub fn walk_ptrs_ty(ty: ty::Ty) -> ty::Ty {
532 ty::TyRef(_, ref tm) |
533 ty::TyRawPtr(ref tm) => walk_ptrs_ty(tm.ty),
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) {
542 ty::TyRef(_, ref tm) |
543 ty::TyRawPtr(ref tm) => inner(tm.ty, depth + 1),
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 {
561 pub fn is_adjusted(cx: &LateContext, e: &Expr) -> bool {
562 cx.tcx.tables.borrow().adjustments.get(&e.id).is_some()
565 pub struct LimitStack {
569 impl Drop for LimitStack {
571 assert_eq!(self.stack.len(), 1);
576 pub fn new(limit: u64) -> LimitStack {
577 LimitStack { stack: vec![limit] }
579 pub fn limit(&self) -> u64 {
580 *self.stack.last().expect("there should always be a value in the stack")
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));
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)));
592 fn parse_attrs<F: FnMut(u64)>(sess: &Session, attrs: &[ast::Attribute], name: &'static str, mut f: F) {
594 let attr = &attr.node;
595 if attr.is_sugared_doc {
598 if let ast::MetaItemKind::NameValue(ref key, ref value) = attr.value.node {
600 if let LitKind::Str(ref s, _) = value.node {
601 if let Ok(value) = FromStr::from_str(s) {
604 sess.span_err(value.span, "not a number");
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> {
618 let span_name_span = cx.tcx
621 .with_expn_info(span.expn_id, |expn| expn.map(|ei| (ei.callee.name(), ei.call_site)));
623 match span_name_span {
624 Some((mac_name, new_span)) if mac_name.as_str() == name => return Some(new_span),
626 Some((_, new_span)) => span = new_span,
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
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
642 .with_expn_info(span.expn_id, |expn| expn.map(|ei| (ei.callee.name(), ei.call_site)));
644 match span_name_span {
645 Some((mac_name, new_span)) if mac_name.as_str() == name => Some(new_span),
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() {
664 if c.is_lowercase() {
669 } else if c.is_uppercase() {
672 } else if !c.is_lowercase() {
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() {
694 let mut last_i = s.len();
697 if c.is_uppercase() {
700 } else if !c.is_lowercase() {
703 } else if c.is_lowercase() {
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,
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 {
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))
741 Some(unwrap_unstable(expr))
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.
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 {
753 limits: RangeLimits::HalfOpen,
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),
764 limits: RangeLimits::HalfOpen,
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,
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,
778 } else if match_path(path, &paths::RANGE_TO_INCLUSIVE_STD) || match_path(path, &paths::RANGE_TO_INCLUSIVE) {
779 Some(UnsugaredRange {
781 end: get_field("end", fields),
782 limits: RangeLimits::Closed,
784 } else if match_path(path, &paths::RANGE_TO_STD) || match_path(path, &paths::RANGE_TO) {
785 Some(UnsugaredRange {
787 end: get_field("end", fields),
788 limits: RangeLimits::HalfOpen,
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 {
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()
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)> {
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,
838 return Some((&somepats[0],
840 &innerarms[0].body));