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::str::FromStr;
16 use syntax::ast::{self, LitKind, RangeLimits};
17 use syntax::codemap::{ExpnInfo, Span, ExpnFormat};
18 use syntax::errors::DiagnosticBuilder;
28 pub use self::hir::{SpanlessEq, SpanlessHash};
30 pub type MethodArgs = HirVec<P<Expr>>;
32 /// Produce a nested chain of if-lets and ifs from the patterns:
44 /// if let Some(y) = x {
46 /// if let Some(z) = y {
52 macro_rules! if_let_chain {
53 ([let $pat:pat = $expr:expr, $($tt:tt)+], $block:block) => {
55 if_let_chain!{ [$($tt)+], $block }
58 ([let $pat:pat = $expr:expr], $block:block) => {
63 ([let $pat:pat = $expr:expr,], $block:block) => {
68 ([$expr:expr, $($tt:tt)+], $block:block) => {
70 if_let_chain!{ [$($tt)+], $block }
73 ([$expr:expr], $block:block) => {
78 ([$expr:expr,], $block:block) => {
85 /// Returns true if the two spans come from differing expansions (i.e. one is from a macro and one
87 pub fn differing_macro_contexts(lhs: Span, rhs: Span) -> bool {
88 rhs.expn_id != lhs.expn_id
90 /// Returns true if this `expn_info` was expanded by any macro.
91 pub fn in_macro<T: LintContext>(cx: &T, span: Span) -> bool {
92 cx.sess().codemap().with_expn_info(span.expn_id, |info| info.is_some())
95 /// Returns true if the macro that expanded the crate was outside of the current crate or was a
97 pub fn in_external_macro<T: LintContext>(cx: &T, span: Span) -> bool {
98 /// Invokes `in_macro` with the expansion info of the given span slightly heavy, try to use
99 /// this after other checks have already happened.
100 fn in_macro_ext<T: LintContext>(cx: &T, opt_info: Option<&ExpnInfo>) -> bool {
101 // no ExpnInfo = no macro
102 opt_info.map_or(false, |info| {
103 if let ExpnFormat::MacroAttribute(..) = info.callee.format {
104 // these are all plugins
107 // no span for the callee = external macro
108 info.callee.span.map_or(true, |span| {
109 // no snippet = external macro or compiler-builtin expansion
110 cx.sess().codemap().span_to_snippet(span).ok().map_or(true, |code| !code.starts_with("macro_rules"))
115 cx.sess().codemap().with_expn_info(span.expn_id, |info| in_macro_ext(cx, info))
118 /// Check if a `DefId`'s path matches the given absolute type path usage.
122 /// match_def_path(cx, id, &["core", "option", "Option"])
125 /// See also the `paths` module.
126 pub fn match_def_path(cx: &LateContext, def_id: DefId, path: &[&str]) -> bool {
127 use syntax::parse::token;
129 struct AbsolutePathBuffer {
130 names: Vec<token::InternedString>,
133 impl ty::item_path::ItemPathBuffer for AbsolutePathBuffer {
134 fn root_mode(&self) -> &ty::item_path::RootMode {
135 const ABSOLUTE: &'static ty::item_path::RootMode = &ty::item_path::RootMode::Absolute;
139 fn push(&mut self, text: &str) {
140 self.names.push(token::intern(text).as_str());
144 let mut apb = AbsolutePathBuffer { names: vec![] };
146 cx.tcx.push_item_path(&mut apb, def_id);
151 /// Check if type is struct or enum type with given def path.
152 pub fn match_type(cx: &LateContext, ty: ty::Ty, path: &[&str]) -> bool {
154 ty::TyEnum(ref adt, _) |
155 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.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 cx.tcx.infer_ctxt(None, None, ProjectionMode::Any).enter(|infcx| {
275 let obligation = cx.tcx.predicate_for_trait_def(traits::ObligationCause::dummy(),
281 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 {
325 let DeclLocal(ref loc) = decl.node,
326 let Some(ref expr) = loc.init,
327 let ExprMatch(_, _, MatchSource::ForLoopDesugar) = expr.node
335 /// Convert a span to a code snippet if available, otherwise use default.
339 /// snippet(cx, expr.span, "..")
341 pub fn snippet<'a, T: LintContext>(cx: &T, span: Span, default: &'a str) -> Cow<'a, str> {
342 cx.sess().codemap().span_to_snippet(span).map(From::from).unwrap_or_else(|_| Cow::Borrowed(default))
345 /// Convert a span to a code snippet. Returns `None` if not available.
346 pub fn snippet_opt<T: LintContext>(cx: &T, span: Span) -> Option<String> {
347 cx.sess().codemap().span_to_snippet(span).ok()
350 /// Convert a span (from a block) to a code snippet if available, otherwise use default.
351 /// This trims the code of indentation, except for the first line. Use it for blocks or block-like
352 /// things which need to be printed as such.
356 /// snippet(cx, expr.span, "..")
358 pub fn snippet_block<'a, T: LintContext>(cx: &T, span: Span, default: &'a str) -> Cow<'a, str> {
359 let snip = snippet(cx, span, default);
360 trim_multiline(snip, true)
363 /// Like `snippet_block`, but add braces if the expr is not an `ExprBlock`.
364 /// Also takes an `Option<String>` which can be put inside the braces.
365 pub fn expr_block<'a, T: LintContext>(cx: &T, expr: &Expr, option: Option<String>, default: &'a str) -> Cow<'a, str> {
366 let code = snippet_block(cx, expr.span, default);
367 let string = option.unwrap_or_default();
368 if let ExprBlock(_) = expr.node {
369 Cow::Owned(format!("{}{}", code, string))
370 } else if string.is_empty() {
371 Cow::Owned(format!("{{ {} }}", code))
373 Cow::Owned(format!("{{\n{};\n{}\n}}", code, string))
377 /// Trim indentation from a multiline string with possibility of ignoring the first line.
378 pub fn trim_multiline(s: Cow<str>, ignore_first: bool) -> Cow<str> {
379 let s_space = trim_multiline_inner(s, ignore_first, ' ');
380 let s_tab = trim_multiline_inner(s_space, ignore_first, '\t');
381 trim_multiline_inner(s_tab, ignore_first, ' ')
384 fn trim_multiline_inner(s: Cow<str>, ignore_first: bool, ch: char) -> Cow<str> {
386 .skip(ignore_first as usize)
391 // ignore empty lines
392 Some(l.char_indices()
393 .find(|&(_, x)| x != ch)
394 .unwrap_or((l.len(), ch))
404 if (ignore_first && i == 0) || l.is_empty() {
417 /// Get a parent expressions if any – this is useful to constrain a lint.
418 pub fn get_parent_expr<'c>(cx: &'c LateContext, e: &Expr) -> Option<&'c Expr> {
419 let map = &cx.tcx.map;
420 let node_id: NodeId = e.id;
421 let parent_id: NodeId = map.get_parent_node(node_id);
422 if node_id == parent_id {
425 map.find(parent_id).and_then(|node| {
426 if let Node::NodeExpr(parent) = node {
434 pub fn get_enclosing_block<'c>(cx: &'c LateContext, node: NodeId) -> Option<&'c Block> {
435 let map = &cx.tcx.map;
436 let enclosing_node = map.get_enclosing_scope(node)
437 .and_then(|enclosing_id| map.find(enclosing_id));
438 if let Some(node) = enclosing_node {
440 Node::NodeBlock(ref block) => Some(block),
441 Node::NodeItem(&Item { node: ItemFn(_, _, _, _, _, ref block), .. }) => Some(block),
449 pub struct DiagnosticWrapper<'a>(pub DiagnosticBuilder<'a>);
451 impl<'a> Drop for DiagnosticWrapper<'a> {
457 impl<'a> DiagnosticWrapper<'a> {
458 fn wiki_link(&mut self, lint: &'static Lint) {
459 if env::var("CLIPPY_DISABLE_WIKI_LINKS").is_err() {
460 self.0.help(&format!("for further information visit https://github.com/Manishearth/rust-clippy/wiki#{}",
466 pub fn span_lint<T: LintContext>(cx: &T, lint: &'static Lint, sp: Span, msg: &str) {
467 let mut db = DiagnosticWrapper(cx.struct_span_lint(lint, sp, msg));
468 if cx.current_level(lint) != Level::Allow {
473 // FIXME: needless lifetime doesn't trigger here
474 pub fn span_help_and_lint<'a, T: LintContext>(cx: &'a T, lint: &'static Lint, span: Span, msg: &str, help: &str) {
475 let mut db = DiagnosticWrapper(cx.struct_span_lint(lint, span, msg));
476 if cx.current_level(lint) != Level::Allow {
482 pub fn span_note_and_lint<'a, T: LintContext>(cx: &'a T, lint: &'static Lint, span: Span, msg: &str, note_span: Span,
484 let mut db = DiagnosticWrapper(cx.struct_span_lint(lint, span, msg));
485 if cx.current_level(lint) != Level::Allow {
486 if note_span == span {
489 db.0.span_note(note_span, note);
495 pub fn span_lint_and_then<'a, T: LintContext, F>(cx: &'a T, lint: &'static Lint, sp: Span, msg: &str, f: F)
496 where F: FnOnce(&mut DiagnosticBuilder<'a>)
498 let mut db = DiagnosticWrapper(cx.struct_span_lint(lint, sp, msg));
499 if cx.current_level(lint) != Level::Allow {
505 /// Return the base type for references and raw pointers.
506 pub fn walk_ptrs_ty(ty: ty::Ty) -> ty::Ty {
508 ty::TyRef(_, ref tm) => walk_ptrs_ty(tm.ty),
513 /// Return the base type for references and raw pointers, and count reference depth.
514 pub fn walk_ptrs_ty_depth(ty: ty::Ty) -> (ty::Ty, usize) {
515 fn inner(ty: ty::Ty, depth: usize) -> (ty::Ty, usize) {
517 ty::TyRef(_, ref tm) => inner(tm.ty, depth + 1),
524 /// Check whether the given expression is a constant literal of the given value.
525 pub fn is_integer_literal(expr: &Expr, value: u64) -> bool {
526 // FIXME: use constant folding
527 if let ExprLit(ref spanned) = expr.node {
528 if let LitKind::Int(v, _) = spanned.node {
535 pub fn is_adjusted(cx: &LateContext, e: &Expr) -> bool {
536 cx.tcx.tables.borrow().adjustments.get(&e.id).is_some()
539 pub struct LimitStack {
543 impl Drop for LimitStack {
545 assert_eq!(self.stack.len(), 1);
550 pub fn new(limit: u64) -> LimitStack {
551 LimitStack { stack: vec![limit] }
553 pub fn limit(&self) -> u64 {
554 *self.stack.last().expect("there should always be a value in the stack")
556 pub fn push_attrs(&mut self, sess: &Session, attrs: &[ast::Attribute], name: &'static str) {
557 let stack = &mut self.stack;
558 parse_attrs(sess, attrs, name, |val| stack.push(val));
560 pub fn pop_attrs(&mut self, sess: &Session, attrs: &[ast::Attribute], name: &'static str) {
561 let stack = &mut self.stack;
562 parse_attrs(sess, attrs, name, |val| assert_eq!(stack.pop(), Some(val)));
566 fn parse_attrs<F: FnMut(u64)>(sess: &Session, attrs: &[ast::Attribute], name: &'static str, mut f: F) {
568 let attr = &attr.node;
569 if attr.is_sugared_doc {
572 if let ast::MetaItemKind::NameValue(ref key, ref value) = attr.value.node {
574 if let LitKind::Str(ref s, _) = value.node {
575 if let Ok(value) = FromStr::from_str(s) {
578 sess.span_err(value.span, "not a number");
588 /// Return the pre-expansion span if is this comes from an expansion of the macro `name`.
589 /// See also `is_direct_expn_of`.
590 pub fn is_expn_of(cx: &LateContext, mut span: Span, name: &str) -> Option<Span> {
592 let span_name_span = cx.tcx
595 .with_expn_info(span.expn_id, |expn| expn.map(|ei| (ei.callee.name(), ei.call_site)));
597 match span_name_span {
598 Some((mac_name, new_span)) if mac_name.as_str() == name => return Some(new_span),
600 Some((_, new_span)) => span = new_span,
605 /// Return the pre-expansion span if is this directly comes from an expansion of the macro `name`.
606 /// The difference with `is_expn_of` is that in
610 /// `42` is considered expanded from `foo!` and `bar!` by `is_expn_of` but only `bar!` by
611 /// `is_direct_expn_of`.
612 pub fn is_direct_expn_of(cx: &LateContext, span: Span, name: &str) -> Option<Span> {
613 let span_name_span = cx.tcx
616 .with_expn_info(span.expn_id, |expn| expn.map(|ei| (ei.callee.name(), ei.call_site)));
618 match span_name_span {
619 Some((mac_name, new_span)) if mac_name.as_str() == name => Some(new_span),
624 /// Return the index of the character after the first camel-case component of `s`.
625 pub fn camel_case_until(s: &str) -> usize {
626 let mut iter = s.char_indices();
627 if let Some((_, first)) = iter.next() {
628 if !first.is_uppercase() {
638 if c.is_lowercase() {
643 } else if c.is_uppercase() {
646 } else if !c.is_lowercase() {
657 /// Return index of the last camel-case component of `s`.
658 pub fn camel_case_from(s: &str) -> usize {
659 let mut iter = s.char_indices().rev();
660 if let Some((_, first)) = iter.next() {
661 if !first.is_lowercase() {
668 let mut last_i = s.len();
671 if c.is_uppercase() {
674 } else if !c.is_lowercase() {
677 } else if c.is_lowercase() {
686 /// Represent a range akin to `ast::ExprKind::Range`.
687 #[derive(Debug, Copy, Clone)]
688 pub struct UnsugaredRange<'a> {
689 pub start: Option<&'a Expr>,
690 pub end: Option<&'a Expr>,
691 pub limits: RangeLimits,
694 /// Unsugar a `hir` range.
695 pub fn unsugar_range(expr: &Expr) -> Option<UnsugaredRange> {
696 // To be removed when ranges get stable.
697 fn unwrap_unstable(expr: &Expr) -> &Expr {
698 if let ExprBlock(ref block) = expr.node {
699 if block.rules == BlockCheckMode::PushUnstableBlock || block.rules == BlockCheckMode::PopUnstableBlock {
700 if let Some(ref expr) = block.expr {
709 fn get_field<'a>(name: &str, fields: &'a [Field]) -> Option<&'a Expr> {
710 let expr = &fields.iter()
711 .find(|field| field.name.node.as_str() == name)
712 .unwrap_or_else(|| panic!("missing {} field for range", name))
715 Some(unwrap_unstable(expr))
718 // The range syntax is expanded to literal paths starting with `core` or `std` depending on
719 // `#[no_std]`. Testing both instead of resolving the paths.
721 match unwrap_unstable(expr).node {
722 ExprPath(None, ref path) => {
723 if match_path(path, &paths::RANGE_FULL_STD) || match_path(path, &paths::RANGE_FULL) {
724 Some(UnsugaredRange {
727 limits: RangeLimits::HalfOpen,
733 ExprStruct(ref path, ref fields, None) => {
734 if match_path(path, &paths::RANGE_FROM_STD) || match_path(path, &paths::RANGE_FROM) {
735 Some(UnsugaredRange {
736 start: get_field("start", fields),
738 limits: RangeLimits::HalfOpen,
740 } else if match_path(path, &paths::RANGE_INCLUSIVE_NON_EMPTY_STD) ||
741 match_path(path, &paths::RANGE_INCLUSIVE_NON_EMPTY) {
742 Some(UnsugaredRange {
743 start: get_field("start", fields),
744 end: get_field("end", fields),
745 limits: RangeLimits::Closed,
747 } else if match_path(path, &paths::RANGE_STD) || match_path(path, &paths::RANGE) {
748 Some(UnsugaredRange {
749 start: get_field("start", fields),
750 end: get_field("end", fields),
751 limits: RangeLimits::HalfOpen,
753 } else if match_path(path, &paths::RANGE_TO_INCLUSIVE_STD) || match_path(path, &paths::RANGE_TO_INCLUSIVE) {
754 Some(UnsugaredRange {
756 end: get_field("end", fields),
757 limits: RangeLimits::Closed,
759 } else if match_path(path, &paths::RANGE_TO_STD) || match_path(path, &paths::RANGE_TO) {
760 Some(UnsugaredRange {
762 end: get_field("end", fields),
763 limits: RangeLimits::HalfOpen,
773 /// Convenience function to get the return type of a function or `None` if the function diverges.
774 pub fn return_ty<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, fn_item: NodeId) -> Option<ty::Ty<'tcx>> {
775 let parameter_env = ty::ParameterEnvironment::for_item(cx.tcx, fn_item);
776 let fn_sig = cx.tcx.node_id_to_type(fn_item).fn_sig().subst(cx.tcx, parameter_env.free_substs);
777 let fn_sig = cx.tcx.liberate_late_bound_regions(parameter_env.free_id_outlive, &fn_sig);
778 if let ty::FnConverging(ret_ty) = fn_sig.output {
785 /// Check if two types are the same.
786 // FIXME: this works correctly for lifetimes bounds (`for <'a> Foo<'a>` == `for <'b> Foo<'b>` but
787 // not for type parameters.
788 pub fn same_tys<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, a: ty::Ty<'tcx>, b: ty::Ty<'tcx>, parameter_item: NodeId) -> bool {
789 let parameter_env = ty::ParameterEnvironment::for_item(cx.tcx, parameter_item);
790 cx.tcx.infer_ctxt(None, Some(parameter_env), ProjectionMode::Any).enter(|infcx| {
791 let new_a = a.subst(infcx.tcx, infcx.parameter_environment.free_substs);
792 let new_b = b.subst(infcx.tcx, infcx.parameter_environment.free_substs);
793 infcx.can_equate(&new_a, &new_b).is_ok()
797 /// Recover the essential nodes of a desugared for loop:
798 /// `for pat in arg { body }` becomes `(pat, arg, body)`.
799 pub fn recover_for_loop(expr: &Expr) -> Option<(&Pat, &Expr, &Expr)> {
801 let ExprMatch(ref iterexpr, ref arms, _) = expr.node,
802 let ExprCall(_, ref iterargs) = iterexpr.node,
803 iterargs.len() == 1 && arms.len() == 1 && arms[0].guard.is_none(),
804 let ExprLoop(ref block, _) = arms[0].body.node,
805 block.stmts.is_empty(),
806 let Some(ref loopexpr) = block.expr,
807 let ExprMatch(_, ref innerarms, MatchSource::ForLoopDesugar) = loopexpr.node,
808 innerarms.len() == 2 && innerarms[0].pats.len() == 1,
809 let PatKind::TupleStruct(_, ref somepats, _) = innerarms[0].pats[0].node,
812 return Some((&somepats[0],
814 &innerarms[0].body));