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;
16 use std::str::FromStr;
17 use syntax::ast::{self, LitKind};
18 use syntax::codemap::{ExpnFormat, ExpnInfo, MultiSpan, Span};
19 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) => {
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 { names: vec![] };
148 cx.tcx.push_item_path(&mut apb, def_id);
153 /// Check if type is struct or enum type with given def path.
154 pub fn match_type(cx: &LateContext, ty: ty::Ty, path: &[&str]) -> bool {
156 ty::TyEnum(ref adt, _) |
157 ty::TyStruct(ref adt, _) => match_def_path(cx, adt.did, path),
162 /// Check if the method call given in `expr` belongs to given type.
163 pub fn match_impl_method(cx: &LateContext, expr: &Expr, path: &[&str]) -> bool {
164 let method_call = ty::MethodCall::expr(expr.id);
171 .and_then(|callee| cx.tcx.impl_of_method(callee.def_id));
172 if let Some(trt_id) = trt_id {
173 match_def_path(cx, trt_id, path)
179 /// Check if the method call given in `expr` belongs to given trait.
180 pub fn match_trait_method(cx: &LateContext, expr: &Expr, path: &[&str]) -> bool {
181 let method_call = ty::MethodCall::expr(expr.id);
188 .and_then(|callee| cx.tcx.trait_of_item(callee.def_id));
189 if let Some(trt_id) = trt_id {
190 match_def_path(cx, trt_id, path)
196 /// Match a `Path` against a slice of segment string literals.
200 /// match_path(path, &["std", "rt", "begin_unwind"])
202 pub fn match_path(path: &Path, segments: &[&str]) -> bool {
203 path.segments.iter().rev().zip(segments.iter().rev()).all(|(a, b)| a.name.as_str() == *b)
206 /// Match a `Path` against a slice of segment string literals, e.g.
210 /// match_path(path, &["std", "rt", "begin_unwind"])
212 pub fn match_path_ast(path: &ast::Path, segments: &[&str]) -> bool {
213 path.segments.iter().rev().zip(segments.iter().rev()).all(|(a, b)| a.identifier.name.as_str() == *b)
216 /// Get the definition associated to a path.
217 /// TODO: investigate if there is something more efficient for that.
218 pub fn path_to_def(cx: &LateContext, path: &[&str]) -> Option<cstore::DefLike> {
219 let cstore = &cx.tcx.sess.cstore;
221 let crates = cstore.crates();
222 let krate = crates.iter().find(|&&krate| cstore.crate_name(krate) == path[0]);
223 if let Some(krate) = krate {
224 let mut items = cstore.crate_top_level_items(*krate);
225 let mut path_it = path.iter().skip(1).peekable();
228 let segment = match path_it.next() {
229 Some(segment) => segment,
233 for item in &mem::replace(&mut items, vec![]) {
234 if item.name.as_str() == *segment {
235 if path_it.peek().is_none() {
236 return Some(item.def);
239 let def_id = match item.def {
240 cstore::DefLike::DlDef(def) => def.def_id(),
241 cstore::DefLike::DlImpl(def_id) => def_id,
242 _ => panic!("Unexpected {:?}", item.def),
245 items = cstore.item_children(def_id);
255 /// Convenience function to get the `DefId` of a trait by path.
256 pub fn get_trait_def_id(cx: &LateContext, path: &[&str]) -> Option<DefId> {
257 let def = match path_to_def(cx, path) {
263 cstore::DlDef(def::Def::Trait(trait_id)) => Some(trait_id),
268 /// Check whether a type implements a trait.
269 /// See also `get_trait_def_id`.
270 pub fn implements_trait<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, ty: ty::Ty<'tcx>, trait_id: DefId,
271 ty_params: Vec<ty::Ty<'tcx>>)
273 cx.tcx.populate_implementations_for_trait_if_necessary(trait_id);
275 let ty = cx.tcx.erase_regions(&ty);
276 cx.tcx.infer_ctxt(None, None, ProjectionMode::Any).enter(|infcx| {
277 let obligation = cx.tcx.predicate_for_trait_def(traits::ObligationCause::dummy(),
283 traits::SelectionContext::new(&infcx).evaluate_obligation_conservatively(&obligation)
287 /// Match an `Expr` against a chain of methods, and return the matched `Expr`s.
289 /// For example, if `expr` represents the `.baz()` in `foo.bar().baz()`,
290 /// `matched_method_chain(expr, &["bar", "baz"])` will return a `Vec` containing the `Expr`s for
291 /// `.bar()` and `.baz()`
292 pub fn method_chain_args<'a>(expr: &'a Expr, methods: &[&str]) -> Option<Vec<&'a MethodArgs>> {
293 let mut current = expr;
294 let mut matched = Vec::with_capacity(methods.len());
295 for method_name in methods.iter().rev() {
296 // method chains are stored last -> first
297 if let ExprMethodCall(ref name, _, ref args) = current.node {
298 if name.node.as_str() == *method_name {
299 matched.push(args); // build up `matched` backwards
300 current = &args[0] // go to parent expression
308 matched.reverse(); // reverse `matched`, so that it is in the same order as `methods`
313 /// Get the name of the item the expression is in, if available.
314 pub fn get_item_name(cx: &LateContext, expr: &Expr) -> Option<Name> {
315 let parent_id = cx.tcx.map.get_parent(expr.id);
316 match cx.tcx.map.find(parent_id) {
317 Some(Node::NodeItem(&Item { ref name, .. })) |
318 Some(Node::NodeTraitItem(&TraitItem { ref name, .. })) |
319 Some(Node::NodeImplItem(&ImplItem { ref name, .. })) => Some(*name),
324 /// Convert a span to a code snippet if available, otherwise use default.
328 /// snippet(cx, expr.span, "..")
330 pub fn snippet<'a, T: LintContext>(cx: &T, span: Span, default: &'a str) -> Cow<'a, str> {
331 cx.sess().codemap().span_to_snippet(span).map(From::from).unwrap_or_else(|_| Cow::Borrowed(default))
334 /// Convert a span to a code snippet. Returns `None` if not available.
335 pub fn snippet_opt<T: LintContext>(cx: &T, span: Span) -> Option<String> {
336 cx.sess().codemap().span_to_snippet(span).ok()
339 /// Convert a span (from a block) to a code snippet if available, otherwise use default.
340 /// This trims the code of indentation, except for the first line. Use it for blocks or block-like
341 /// things which need to be printed as such.
345 /// snippet(cx, expr.span, "..")
347 pub fn snippet_block<'a, T: LintContext>(cx: &T, span: Span, default: &'a str) -> Cow<'a, str> {
348 let snip = snippet(cx, span, default);
349 trim_multiline(snip, true)
352 /// Like `snippet_block`, but add braces if the expr is not an `ExprBlock`.
353 /// Also takes an `Option<String>` which can be put inside the braces.
354 pub fn expr_block<'a, T: LintContext>(cx: &T, expr: &Expr, option: Option<String>, default: &'a str) -> Cow<'a, str> {
355 let code = snippet_block(cx, expr.span, default);
356 let string = option.unwrap_or_default();
357 if let ExprBlock(_) = expr.node {
358 Cow::Owned(format!("{}{}", code, string))
359 } else if string.is_empty() {
360 Cow::Owned(format!("{{ {} }}", code))
362 Cow::Owned(format!("{{\n{};\n{}\n}}", code, string))
366 /// Trim indentation from a multiline string with possibility of ignoring the first line.
367 pub fn trim_multiline(s: Cow<str>, ignore_first: bool) -> Cow<str> {
368 let s_space = trim_multiline_inner(s, ignore_first, ' ');
369 let s_tab = trim_multiline_inner(s_space, ignore_first, '\t');
370 trim_multiline_inner(s_tab, ignore_first, ' ')
373 fn trim_multiline_inner(s: Cow<str>, ignore_first: bool, ch: char) -> Cow<str> {
375 .skip(ignore_first as usize)
380 // ignore empty lines
381 Some(l.char_indices()
382 .find(|&(_, x)| x != ch)
383 .unwrap_or((l.len(), ch))
393 if (ignore_first && i == 0) || l.is_empty() {
406 /// Get a parent expressions if any – this is useful to constrain a lint.
407 pub fn get_parent_expr<'c>(cx: &'c LateContext, e: &Expr) -> Option<&'c Expr> {
408 let map = &cx.tcx.map;
409 let node_id: NodeId = e.id;
410 let parent_id: NodeId = map.get_parent_node(node_id);
411 if node_id == parent_id {
414 map.find(parent_id).and_then(|node| {
415 if let Node::NodeExpr(parent) = node {
423 pub fn get_enclosing_block<'c>(cx: &'c LateContext, node: NodeId) -> Option<&'c Block> {
424 let map = &cx.tcx.map;
425 let enclosing_node = map.get_enclosing_scope(node)
426 .and_then(|enclosing_id| map.find(enclosing_id));
427 if let Some(node) = enclosing_node {
429 Node::NodeBlock(ref block) => Some(block),
430 Node::NodeItem(&Item { node: ItemFn(_, _, _, _, _, ref block), .. }) => Some(block),
438 pub struct DiagnosticWrapper<'a>(pub DiagnosticBuilder<'a>);
440 impl<'a> Drop for DiagnosticWrapper<'a> {
446 impl<'a> DiagnosticWrapper<'a> {
447 fn wiki_link(&mut self, lint: &'static Lint) {
448 if env::var("CLIPPY_DISABLE_WIKI_LINKS").is_err() {
449 self.0.help(&format!("for further information visit https://github.com/Manishearth/rust-clippy/wiki#{}",
455 pub fn span_lint<T: LintContext>(cx: &T, lint: &'static Lint, sp: Span, msg: &str) {
456 let mut db = DiagnosticWrapper(cx.struct_span_lint(lint, sp, msg));
457 if cx.current_level(lint) != Level::Allow {
462 // FIXME: needless lifetime doesn't trigger here
463 pub fn span_help_and_lint<'a, T: LintContext>(cx: &'a T, lint: &'static Lint, span: Span, msg: &str, help: &str) {
464 let mut db = DiagnosticWrapper(cx.struct_span_lint(lint, span, msg));
465 if cx.current_level(lint) != Level::Allow {
471 pub fn span_note_and_lint<'a, T: LintContext>(cx: &'a T, lint: &'static Lint, span: Span, msg: &str, note_span: Span,
473 let mut db = DiagnosticWrapper(cx.struct_span_lint(lint, span, msg));
474 if cx.current_level(lint) != Level::Allow {
475 if note_span == span {
478 db.0.span_note(note_span, note);
484 pub fn span_lint_and_then<'a, T: LintContext, F>(cx: &'a T, lint: &'static Lint, sp: Span, msg: &str, f: F)
485 where F: FnOnce(&mut DiagnosticBuilder<'a>)
487 let mut db = DiagnosticWrapper(cx.struct_span_lint(lint, sp, msg));
488 if cx.current_level(lint) != Level::Allow {
494 /// Create a suggestion made from several `span → replacement`.
496 /// Note: in the JSON format (used by `compiletest_rs`), the help message will appear once per
497 /// replacement. In human-readable format though, it only appears once before the whole suggestion.
498 pub fn multispan_sugg(db: &mut DiagnosticBuilder, help_msg: String, sugg: &[(Span, &str)]) {
499 let sugg = rustc_errors::RenderSpan::Suggestion(rustc_errors::CodeSuggestion {
500 msp: MultiSpan::from_spans(sugg.iter().map(|&(span, _)| span).collect()),
501 substitutes: sugg.iter().map(|&(_, subs)| subs.to_owned()).collect(),
504 let sub = rustc_errors::SubDiagnostic {
505 level: rustc_errors::Level::Help,
507 span: MultiSpan::new(),
508 render_span: Some(sugg),
510 db.children.push(sub);
513 /// Return the base type for references and raw pointers.
514 pub fn walk_ptrs_ty(ty: ty::Ty) -> ty::Ty {
516 ty::TyRef(_, ref tm) => walk_ptrs_ty(tm.ty),
521 /// Return the base type for references and raw pointers, and count reference depth.
522 pub fn walk_ptrs_ty_depth(ty: ty::Ty) -> (ty::Ty, usize) {
523 fn inner(ty: ty::Ty, depth: usize) -> (ty::Ty, usize) {
525 ty::TyRef(_, ref tm) => inner(tm.ty, depth + 1),
532 /// Check whether the given expression is a constant literal of the given value.
533 pub fn is_integer_literal(expr: &Expr, value: u64) -> bool {
534 // FIXME: use constant folding
535 if let ExprLit(ref spanned) = expr.node {
536 if let LitKind::Int(v, _) = spanned.node {
543 pub fn is_adjusted(cx: &LateContext, e: &Expr) -> bool {
544 cx.tcx.tables.borrow().adjustments.get(&e.id).is_some()
547 pub struct LimitStack {
551 impl Drop for LimitStack {
553 assert_eq!(self.stack.len(), 1);
558 pub fn new(limit: u64) -> LimitStack {
559 LimitStack { stack: vec![limit] }
561 pub fn limit(&self) -> u64 {
562 *self.stack.last().expect("there should always be a value in the stack")
564 pub fn push_attrs(&mut self, sess: &Session, attrs: &[ast::Attribute], name: &'static str) {
565 let stack = &mut self.stack;
566 parse_attrs(sess, attrs, name, |val| stack.push(val));
568 pub fn pop_attrs(&mut self, sess: &Session, attrs: &[ast::Attribute], name: &'static str) {
569 let stack = &mut self.stack;
570 parse_attrs(sess, attrs, name, |val| assert_eq!(stack.pop(), Some(val)));
574 fn parse_attrs<F: FnMut(u64)>(sess: &Session, attrs: &[ast::Attribute], name: &'static str, mut f: F) {
576 let attr = &attr.node;
577 if attr.is_sugared_doc {
580 if let ast::MetaItemKind::NameValue(ref key, ref value) = attr.value.node {
582 if let LitKind::Str(ref s, _) = value.node {
583 if let Ok(value) = FromStr::from_str(s) {
586 sess.span_err(value.span, "not a number");
596 /// Return the pre-expansion span if is this comes from an expansion of the macro `name`.
597 /// See also `is_direct_expn_of`.
598 pub fn is_expn_of(cx: &LateContext, mut span: Span, name: &str) -> Option<Span> {
600 let span_name_span = cx.tcx
603 .with_expn_info(span.expn_id, |expn| expn.map(|ei| (ei.callee.name(), ei.call_site)));
605 match span_name_span {
606 Some((mac_name, new_span)) if mac_name.as_str() == name => return Some(new_span),
608 Some((_, new_span)) => span = new_span,
613 /// Return the pre-expansion span if is this directly comes from an expansion of the macro `name`.
614 /// The difference with `is_expn_of` is that in
618 /// `42` is considered expanded from `foo!` and `bar!` by `is_expn_of` but only `bar!` by
619 /// `is_direct_expn_of`.
620 pub fn is_direct_expn_of(cx: &LateContext, span: Span, name: &str) -> Option<Span> {
621 let span_name_span = cx.tcx
624 .with_expn_info(span.expn_id, |expn| expn.map(|ei| (ei.callee.name(), ei.call_site)));
626 match span_name_span {
627 Some((mac_name, new_span)) if mac_name.as_str() == name => Some(new_span),
632 /// Return the index of the character after the first camel-case component of `s`.
633 pub fn camel_case_until(s: &str) -> usize {
634 let mut iter = s.char_indices();
635 if let Some((_, first)) = iter.next() {
636 if !first.is_uppercase() {
646 if c.is_lowercase() {
651 } else if c.is_uppercase() {
654 } else if !c.is_lowercase() {
665 /// Return index of the last camel-case component of `s`.
666 pub fn camel_case_from(s: &str) -> usize {
667 let mut iter = s.char_indices().rev();
668 if let Some((_, first)) = iter.next() {
669 if !first.is_lowercase() {
676 let mut last_i = s.len();
679 if c.is_uppercase() {
682 } else if !c.is_lowercase() {
685 } else if c.is_lowercase() {
694 /// Convenience function to get the return type of a function or `None` if the function diverges.
695 pub fn return_ty<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, fn_item: NodeId) -> Option<ty::Ty<'tcx>> {
696 let parameter_env = ty::ParameterEnvironment::for_item(cx.tcx, fn_item);
697 let fn_sig = cx.tcx.node_id_to_type(fn_item).fn_sig().subst(cx.tcx, parameter_env.free_substs);
698 let fn_sig = cx.tcx.liberate_late_bound_regions(parameter_env.free_id_outlive, &fn_sig);
699 if let ty::FnConverging(ret_ty) = fn_sig.output {
706 /// Check if two types are the same.
707 // FIXME: this works correctly for lifetimes bounds (`for <'a> Foo<'a>` == `for <'b> Foo<'b>` but
708 // not for type parameters.
709 pub fn same_tys<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, a: ty::Ty<'tcx>, b: ty::Ty<'tcx>, parameter_item: NodeId) -> bool {
710 let parameter_env = ty::ParameterEnvironment::for_item(cx.tcx, parameter_item);
711 cx.tcx.infer_ctxt(None, Some(parameter_env), ProjectionMode::Any).enter(|infcx| {
712 let new_a = a.subst(infcx.tcx, infcx.parameter_environment.free_substs);
713 let new_b = b.subst(infcx.tcx, infcx.parameter_environment.free_substs);
714 infcx.can_equate(&new_a, &new_b).is_ok()