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:
43 /// if let Some(y) = x {
45 /// if let Some(z) = y {
51 macro_rules! if_let_chain {
52 ([let $pat:pat = $expr:expr, $($tt:tt)+], $block:block) => {
54 if_let_chain!{ [$($tt)+], $block }
57 ([let $pat:pat = $expr:expr], $block:block) => {
62 ([let $pat:pat = $expr:expr,], $block:block) => {
67 ([$expr:expr, $($tt:tt)+], $block:block) => {
69 if_let_chain!{ [$($tt)+], $block }
72 ([$expr:expr], $block:block) => {
77 ([$expr:expr,], $block:block) => {
84 /// Returns true if the two spans come from differing expansions (i.e. one is from a macro and one
86 pub fn differing_macro_contexts(lhs: Span, rhs: Span) -> bool {
87 rhs.expn_id != lhs.expn_id
89 /// Returns true if this `expn_info` was expanded by any macro.
90 pub fn in_macro<T: LintContext>(cx: &T, span: Span) -> bool {
91 cx.sess().codemap().with_expn_info(span.expn_id, |info| info.is_some())
94 /// Returns true if the macro that expanded the crate was outside of the current crate or was a
96 pub fn in_external_macro<T: LintContext>(cx: &T, span: Span) -> bool {
97 /// Invokes `in_macro` with the expansion info of the given span slightly heavy, try to use
98 /// this after other checks have already happened.
99 fn in_macro_ext<T: LintContext>(cx: &T, opt_info: Option<&ExpnInfo>) -> bool {
100 // no ExpnInfo = no macro
101 opt_info.map_or(false, |info| {
102 if let ExpnFormat::MacroAttribute(..) = info.callee.format {
103 // these are all plugins
106 // no span for the callee = external macro
107 info.callee.span.map_or(true, |span| {
108 // no snippet = external macro or compiler-builtin expansion
109 cx.sess().codemap().span_to_snippet(span).ok().map_or(true, |code| !code.starts_with("macro_rules"))
114 cx.sess().codemap().with_expn_info(span.expn_id, |info| in_macro_ext(cx, info))
117 /// Check if a `DefId`'s path matches the given absolute type path usage.
121 /// match_def_path(cx, id, &["core", "option", "Option"])
124 /// See also the `paths` module.
125 pub fn match_def_path(cx: &LateContext, def_id: DefId, path: &[&str]) -> bool {
126 use syntax::parse::token;
128 struct AbsolutePathBuffer {
129 names: Vec<token::InternedString>,
132 impl ty::item_path::ItemPathBuffer for AbsolutePathBuffer {
133 fn root_mode(&self) -> &ty::item_path::RootMode {
134 const ABSOLUTE: &'static ty::item_path::RootMode = &ty::item_path::RootMode::Absolute;
138 fn push(&mut self, text: &str) {
139 self.names.push(token::intern(text).as_str());
143 let mut apb = AbsolutePathBuffer { names: vec![] };
145 cx.tcx.push_item_path(&mut apb, def_id);
150 /// Check if type is struct or enum type with given def path.
151 pub fn match_type(cx: &LateContext, ty: ty::Ty, path: &[&str]) -> bool {
153 ty::TyEnum(ref adt, _) |
154 ty::TyStruct(ref adt, _) => match_def_path(cx, adt.did, path),
159 /// Check if the method call given in `expr` belongs to given type.
160 pub fn match_impl_method(cx: &LateContext, expr: &Expr, path: &[&str]) -> bool {
161 let method_call = ty::MethodCall::expr(expr.id);
168 .and_then(|callee| cx.tcx.impl_of_method(callee.def_id));
169 if let Some(trt_id) = trt_id {
170 match_def_path(cx, trt_id, path)
176 /// Check if the method call given in `expr` belongs to given trait.
177 pub fn match_trait_method(cx: &LateContext, expr: &Expr, path: &[&str]) -> bool {
178 let method_call = ty::MethodCall::expr(expr.id);
185 .and_then(|callee| cx.tcx.trait_of_item(callee.def_id));
186 if let Some(trt_id) = trt_id {
187 match_def_path(cx, trt_id, path)
193 /// Match a `Path` against a slice of segment string literals.
197 /// match_path(path, &["std", "rt", "begin_unwind"])
199 pub fn match_path(path: &Path, segments: &[&str]) -> bool {
200 path.segments.iter().rev().zip(segments.iter().rev()).all(|(a, b)| a.name.as_str() == *b)
203 /// Match a `Path` against a slice of segment string literals, e.g.
207 /// match_path(path, &["std", "rt", "begin_unwind"])
209 pub fn match_path_ast(path: &ast::Path, segments: &[&str]) -> bool {
210 path.segments.iter().rev().zip(segments.iter().rev()).all(|(a, b)| a.identifier.name.as_str() == *b)
213 /// Get the definition associated to a path.
214 /// TODO: investigate if there is something more efficient for that.
215 pub fn path_to_def(cx: &LateContext, path: &[&str]) -> Option<cstore::DefLike> {
216 let cstore = &cx.tcx.sess.cstore;
218 let crates = cstore.crates();
219 let krate = crates.iter().find(|&&krate| cstore.crate_name(krate) == path[0]);
220 if let Some(krate) = krate {
221 let mut items = cstore.crate_top_level_items(*krate);
222 let mut path_it = path.iter().skip(1).peekable();
225 let segment = match path_it.next() {
226 Some(segment) => segment,
230 for item in &mem::replace(&mut items, vec![]) {
231 if item.name.as_str() == *segment {
232 if path_it.peek().is_none() {
233 return Some(item.def);
236 let def_id = match item.def {
237 cstore::DefLike::DlDef(def) => def.def_id(),
238 cstore::DefLike::DlImpl(def_id) => def_id,
239 _ => panic!("Unexpected {:?}", item.def),
242 items = cstore.item_children(def_id);
252 /// Convenience function to get the `DefId` of a trait by path.
253 pub fn get_trait_def_id(cx: &LateContext, path: &[&str]) -> Option<DefId> {
254 let def = match path_to_def(cx, path) {
260 cstore::DlDef(def::Def::Trait(trait_id)) => Some(trait_id),
265 /// Check whether a type implements a trait.
266 /// See also `get_trait_def_id`.
267 pub fn implements_trait<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, ty: ty::Ty<'tcx>, trait_id: DefId,
268 ty_params: Vec<ty::Ty<'tcx>>)
270 cx.tcx.populate_implementations_for_trait_if_necessary(trait_id);
272 let ty = cx.tcx.erase_regions(&ty);
273 cx.tcx.infer_ctxt(None, None, ProjectionMode::Any).enter(|infcx| {
274 let obligation = cx.tcx.predicate_for_trait_def(traits::ObligationCause::dummy(),
280 traits::SelectionContext::new(&infcx).evaluate_obligation_conservatively(&obligation)
284 /// Match an `Expr` against a chain of methods, and return the matched `Expr`s.
286 /// For example, if `expr` represents the `.baz()` in `foo.bar().baz()`,
287 /// `matched_method_chain(expr, &["bar", "baz"])` will return a `Vec` containing the `Expr`s for
288 /// `.bar()` and `.baz()`
289 pub fn method_chain_args<'a>(expr: &'a Expr, methods: &[&str]) -> Option<Vec<&'a MethodArgs>> {
290 let mut current = expr;
291 let mut matched = Vec::with_capacity(methods.len());
292 for method_name in methods.iter().rev() {
293 // method chains are stored last -> first
294 if let ExprMethodCall(ref name, _, ref args) = current.node {
295 if name.node.as_str() == *method_name {
296 matched.push(args); // build up `matched` backwards
297 current = &args[0] // go to parent expression
305 matched.reverse(); // reverse `matched`, so that it is in the same order as `methods`
310 /// Get the name of the item the expression is in, if available.
311 pub fn get_item_name(cx: &LateContext, expr: &Expr) -> Option<Name> {
312 let parent_id = cx.tcx.map.get_parent(expr.id);
313 match cx.tcx.map.find(parent_id) {
314 Some(Node::NodeItem(&Item { ref name, .. })) |
315 Some(Node::NodeTraitItem(&TraitItem { ref name, .. })) |
316 Some(Node::NodeImplItem(&ImplItem { ref name, .. })) => Some(*name),
321 /// Checks if a `let` decl is from a `for` loop desugaring.
322 pub fn is_from_for_desugar(decl: &Decl) -> bool {
324 let DeclLocal(ref loc) = decl.node,
325 let Some(ref expr) = loc.init,
326 let ExprMatch(_, _, MatchSource::ForLoopDesugar) = expr.node
334 /// Convert a span to a code snippet if available, otherwise use default.
338 /// snippet(cx, expr.span, "..")
340 pub fn snippet<'a, T: LintContext>(cx: &T, span: Span, default: &'a str) -> Cow<'a, str> {
341 cx.sess().codemap().span_to_snippet(span).map(From::from).unwrap_or_else(|_| Cow::Borrowed(default))
344 /// Convert a span to a code snippet. Returns `None` if not available.
345 pub fn snippet_opt<T: LintContext>(cx: &T, span: Span) -> Option<String> {
346 cx.sess().codemap().span_to_snippet(span).ok()
349 /// Convert a span (from a block) to a code snippet if available, otherwise use default.
350 /// This trims the code of indentation, except for the first line. Use it for blocks or block-like
351 /// things which need to be printed as such.
355 /// snippet(cx, expr.span, "..")
357 pub fn snippet_block<'a, T: LintContext>(cx: &T, span: Span, default: &'a str) -> Cow<'a, str> {
358 let snip = snippet(cx, span, default);
359 trim_multiline(snip, true)
362 /// Like `snippet_block`, but add braces if the expr is not an `ExprBlock`.
363 /// Also takes an `Option<String>` which can be put inside the braces.
364 pub fn expr_block<'a, T: LintContext>(cx: &T, expr: &Expr, option: Option<String>, default: &'a str) -> Cow<'a, str> {
365 let code = snippet_block(cx, expr.span, default);
366 let string = option.unwrap_or_default();
367 if let ExprBlock(_) = expr.node {
368 Cow::Owned(format!("{}{}", code, string))
369 } else if string.is_empty() {
370 Cow::Owned(format!("{{ {} }}", code))
372 Cow::Owned(format!("{{\n{};\n{}\n}}", code, string))
376 /// Trim indentation from a multiline string with possibility of ignoring the first line.
377 pub fn trim_multiline(s: Cow<str>, ignore_first: bool) -> Cow<str> {
378 let s_space = trim_multiline_inner(s, ignore_first, ' ');
379 let s_tab = trim_multiline_inner(s_space, ignore_first, '\t');
380 trim_multiline_inner(s_tab, ignore_first, ' ')
383 fn trim_multiline_inner(s: Cow<str>, ignore_first: bool, ch: char) -> Cow<str> {
385 .skip(ignore_first as usize)
390 // ignore empty lines
391 Some(l.char_indices()
392 .find(|&(_, x)| x != ch)
393 .unwrap_or((l.len(), ch))
403 if (ignore_first && i == 0) || l.is_empty() {
416 /// Get a parent expressions if any – this is useful to constrain a lint.
417 pub fn get_parent_expr<'c>(cx: &'c LateContext, e: &Expr) -> Option<&'c Expr> {
418 let map = &cx.tcx.map;
419 let node_id: NodeId = e.id;
420 let parent_id: NodeId = map.get_parent_node(node_id);
421 if node_id == parent_id {
424 map.find(parent_id).and_then(|node| {
425 if let Node::NodeExpr(parent) = node {
433 pub fn get_enclosing_block<'c>(cx: &'c LateContext, node: NodeId) -> Option<&'c Block> {
434 let map = &cx.tcx.map;
435 let enclosing_node = map.get_enclosing_scope(node)
436 .and_then(|enclosing_id| map.find(enclosing_id));
437 if let Some(node) = enclosing_node {
439 Node::NodeBlock(ref block) => Some(block),
440 Node::NodeItem(&Item { node: ItemFn(_, _, _, _, _, ref block), .. }) => Some(block),
448 pub struct DiagnosticWrapper<'a>(pub DiagnosticBuilder<'a>);
450 impl<'a> Drop for DiagnosticWrapper<'a> {
456 impl<'a> DerefMut for DiagnosticWrapper<'a> {
457 fn deref_mut(&mut self) -> &mut DiagnosticBuilder<'a> {
462 impl<'a> Deref for DiagnosticWrapper<'a> {
463 type Target = DiagnosticBuilder<'a>;
464 fn deref(&self) -> &DiagnosticBuilder<'a> {
469 impl<'a> DiagnosticWrapper<'a> {
470 fn wiki_link(&mut self, lint: &'static Lint) {
471 if env::var("CLIPPY_DISABLE_WIKI_LINKS").is_err() {
472 self.help(&format!("for further information visit https://github.com/Manishearth/rust-clippy/wiki#{}",
478 pub fn span_lint<'a, T: LintContext>(cx: &'a T, lint: &'static Lint, sp: Span, msg: &str) -> DiagnosticWrapper<'a> {
479 let mut db = DiagnosticWrapper(cx.struct_span_lint(lint, sp, msg));
480 if cx.current_level(lint) != Level::Allow {
486 pub fn span_help_and_lint<'a, T: LintContext>(cx: &'a T, lint: &'static Lint, span: Span, msg: &str, help: &str)
487 -> DiagnosticWrapper<'a> {
488 let mut db = DiagnosticWrapper(cx.struct_span_lint(lint, span, msg));
489 if cx.current_level(lint) != Level::Allow {
496 pub fn span_note_and_lint<'a, T: LintContext>(cx: &'a T, lint: &'static Lint, span: Span, msg: &str, note_span: Span,
498 -> DiagnosticWrapper<'a> {
499 let mut db = DiagnosticWrapper(cx.struct_span_lint(lint, span, msg));
500 if cx.current_level(lint) != Level::Allow {
501 if note_span == span {
504 db.span_note(note_span, note);
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 {
523 /// Return the base type for references and raw pointers.
524 pub fn walk_ptrs_ty(ty: ty::Ty) -> ty::Ty {
526 ty::TyRef(_, ref tm) => walk_ptrs_ty(tm.ty),
531 /// Return the base type for references and raw pointers, and count reference depth.
532 pub fn walk_ptrs_ty_depth(ty: ty::Ty) -> (ty::Ty, usize) {
533 fn inner(ty: ty::Ty, depth: usize) -> (ty::Ty, usize) {
535 ty::TyRef(_, ref tm) => inner(tm.ty, depth + 1),
542 /// Check whether the given expression is a constant literal of the given value.
543 pub fn is_integer_literal(expr: &Expr, value: u64) -> bool {
544 // FIXME: use constant folding
545 if let ExprLit(ref spanned) = expr.node {
546 if let LitKind::Int(v, _) = spanned.node {
553 pub fn is_adjusted(cx: &LateContext, e: &Expr) -> bool {
554 cx.tcx.tables.borrow().adjustments.get(&e.id).is_some()
557 pub struct LimitStack {
561 impl Drop for LimitStack {
563 assert_eq!(self.stack.len(), 1);
568 pub fn new(limit: u64) -> LimitStack {
569 LimitStack { stack: vec![limit] }
571 pub fn limit(&self) -> u64 {
572 *self.stack.last().expect("there should always be a value in the stack")
574 pub fn push_attrs(&mut self, sess: &Session, attrs: &[ast::Attribute], name: &'static str) {
575 let stack = &mut self.stack;
576 parse_attrs(sess, attrs, name, |val| stack.push(val));
578 pub fn pop_attrs(&mut self, sess: &Session, attrs: &[ast::Attribute], name: &'static str) {
579 let stack = &mut self.stack;
580 parse_attrs(sess, attrs, name, |val| assert_eq!(stack.pop(), Some(val)));
584 fn parse_attrs<F: FnMut(u64)>(sess: &Session, attrs: &[ast::Attribute], name: &'static str, mut f: F) {
586 let attr = &attr.node;
587 if attr.is_sugared_doc {
590 if let ast::MetaItemKind::NameValue(ref key, ref value) = attr.value.node {
592 if let LitKind::Str(ref s, _) = value.node {
593 if let Ok(value) = FromStr::from_str(s) {
596 sess.span_err(value.span, "not a number");
606 /// Return the pre-expansion span if is this comes from an expansion of the macro `name`.
607 /// See also `is_direct_expn_of`.
608 pub fn is_expn_of(cx: &LateContext, mut span: Span, name: &str) -> Option<Span> {
610 let span_name_span = cx.tcx
613 .with_expn_info(span.expn_id, |expn| expn.map(|ei| (ei.callee.name(), ei.call_site)));
615 match span_name_span {
616 Some((mac_name, new_span)) if mac_name.as_str() == name => return Some(new_span),
618 Some((_, new_span)) => span = new_span,
623 /// Return the pre-expansion span if is this directly comes from an expansion of the macro `name`.
624 /// The difference with `is_expn_of` is that in
628 /// `42` is considered expanded from `foo!` and `bar!` by `is_expn_of` but only `bar!` by
629 /// `is_direct_expn_of`.
630 pub fn is_direct_expn_of(cx: &LateContext, span: Span, name: &str) -> Option<Span> {
631 let span_name_span = cx.tcx
634 .with_expn_info(span.expn_id, |expn| expn.map(|ei| (ei.callee.name(), ei.call_site)));
636 match span_name_span {
637 Some((mac_name, new_span)) if mac_name.as_str() == name => Some(new_span),
642 /// Return the index of the character after the first camel-case component of `s`.
643 pub fn camel_case_until(s: &str) -> usize {
644 let mut iter = s.char_indices();
645 if let Some((_, first)) = iter.next() {
646 if !first.is_uppercase() {
656 if c.is_lowercase() {
661 } else if c.is_uppercase() {
664 } else if !c.is_lowercase() {
675 /// Return index of the last camel-case component of `s`.
676 pub fn camel_case_from(s: &str) -> usize {
677 let mut iter = s.char_indices().rev();
678 if let Some((_, first)) = iter.next() {
679 if !first.is_lowercase() {
686 let mut last_i = s.len();
689 if c.is_uppercase() {
692 } else if !c.is_lowercase() {
695 } else if c.is_lowercase() {
704 /// Represent a range akin to `ast::ExprKind::Range`.
705 #[derive(Debug, Copy, Clone)]
706 pub struct UnsugaredRange<'a> {
707 pub start: Option<&'a Expr>,
708 pub end: Option<&'a Expr>,
709 pub limits: RangeLimits,
712 /// Unsugar a `hir` range.
713 pub fn unsugar_range(expr: &Expr) -> Option<UnsugaredRange> {
714 // To be removed when ranges get stable.
715 fn unwrap_unstable(expr: &Expr) -> &Expr {
716 if let ExprBlock(ref block) = expr.node {
717 if block.rules == BlockCheckMode::PushUnstableBlock || block.rules == BlockCheckMode::PopUnstableBlock {
718 if let Some(ref expr) = block.expr {
727 fn get_field<'a>(name: &str, fields: &'a [Field]) -> Option<&'a Expr> {
728 let expr = &fields.iter()
729 .find(|field| field.name.node.as_str() == name)
730 .unwrap_or_else(|| panic!("missing {} field for range", name))
733 Some(unwrap_unstable(expr))
736 // The range syntax is expanded to literal paths starting with `core` or `std` depending on
737 // `#[no_std]`. Testing both instead of resolving the paths.
739 match unwrap_unstable(expr).node {
740 ExprPath(None, ref path) => {
741 if match_path(path, &paths::RANGE_FULL_STD) || match_path(path, &paths::RANGE_FULL) {
742 Some(UnsugaredRange {
745 limits: RangeLimits::HalfOpen,
751 ExprStruct(ref path, ref fields, None) => {
752 if match_path(path, &paths::RANGE_FROM_STD) || match_path(path, &paths::RANGE_FROM) {
753 Some(UnsugaredRange {
754 start: get_field("start", fields),
756 limits: RangeLimits::HalfOpen,
758 } else if match_path(path, &paths::RANGE_INCLUSIVE_NON_EMPTY_STD) ||
759 match_path(path, &paths::RANGE_INCLUSIVE_NON_EMPTY) {
760 Some(UnsugaredRange {
761 start: get_field("start", fields),
762 end: get_field("end", fields),
763 limits: RangeLimits::Closed,
765 } else if match_path(path, &paths::RANGE_STD) || match_path(path, &paths::RANGE) {
766 Some(UnsugaredRange {
767 start: get_field("start", fields),
768 end: get_field("end", fields),
769 limits: RangeLimits::HalfOpen,
771 } else if match_path(path, &paths::RANGE_TO_INCLUSIVE_STD) || match_path(path, &paths::RANGE_TO_INCLUSIVE) {
772 Some(UnsugaredRange {
774 end: get_field("end", fields),
775 limits: RangeLimits::Closed,
777 } else if match_path(path, &paths::RANGE_TO_STD) || match_path(path, &paths::RANGE_TO) {
778 Some(UnsugaredRange {
780 end: get_field("end", fields),
781 limits: RangeLimits::HalfOpen,
791 /// Convenience function to get the return type of a function or `None` if the function diverges.
792 pub fn return_ty<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, fn_item: NodeId) -> Option<ty::Ty<'tcx>> {
793 let parameter_env = ty::ParameterEnvironment::for_item(cx.tcx, fn_item);
794 let fn_sig = cx.tcx.node_id_to_type(fn_item).fn_sig().subst(cx.tcx, parameter_env.free_substs);
795 let fn_sig = cx.tcx.liberate_late_bound_regions(parameter_env.free_id_outlive, &fn_sig);
796 if let ty::FnConverging(ret_ty) = fn_sig.output {
803 /// Check if two types are the same.
804 // FIXME: this works correctly for lifetimes bounds (`for <'a> Foo<'a>` == `for <'b> Foo<'b>` but
805 // not for type parameters.
806 pub fn same_tys<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, a: ty::Ty<'tcx>, b: ty::Ty<'tcx>, parameter_item: NodeId) -> bool {
807 let parameter_env = ty::ParameterEnvironment::for_item(cx.tcx, parameter_item);
808 cx.tcx.infer_ctxt(None, Some(parameter_env), ProjectionMode::Any).enter(|infcx| {
809 let new_a = a.subst(infcx.tcx, infcx.parameter_environment.free_substs);
810 let new_b = b.subst(infcx.tcx, infcx.parameter_environment.free_substs);
811 infcx.can_equate(&new_a, &new_b).is_ok()
815 /// Recover the essential nodes of a desugared for loop:
816 /// `for pat in arg { body }` becomes `(pat, arg, body)`.
817 pub fn recover_for_loop(expr: &Expr) -> Option<(&Pat, &Expr, &Expr)> {
819 let ExprMatch(ref iterexpr, ref arms, _) = expr.node,
820 let ExprCall(_, ref iterargs) = iterexpr.node,
821 iterargs.len() == 1 && arms.len() == 1 && arms[0].guard.is_none(),
822 let ExprLoop(ref block, _) = arms[0].body.node,
823 block.stmts.is_empty(),
824 let Some(ref loopexpr) = block.expr,
825 let ExprMatch(_, ref innerarms, MatchSource::ForLoopDesugar) = loopexpr.node,
826 innerarms.len() == 2 && innerarms[0].pats.len() == 1,
827 let PatKind::TupleStruct(_, ref somepats, _) = innerarms[0].pats[0].node,
830 return Some((&somepats[0],
832 &innerarms[0].body));