4 use rustc::hir::def_id::{DefId, CRATE_DEF_INDEX};
5 use rustc::hir::def::Def;
6 use rustc::hir::intravisit::{NestedVisitorMap, Visitor};
7 use rustc::hir::map::Node;
8 use rustc::lint::{LateContext, Level, Lint, LintContext};
9 use rustc::session::Session;
11 use rustc::ty::{self, Ty, TyCtxt};
12 use rustc::mir::transform::MirSource;
17 use std::str::FromStr;
19 use syntax::ast::{self, LitKind};
21 use syntax::codemap::{CompilerDesugaringKind, ExpnFormat, ExpnInfo, Span, DUMMY_SP};
22 use syntax::errors::DiagnosticBuilder;
24 use syntax::symbol::keywords;
33 pub mod internal_lints;
35 pub use self::hir_utils::{SpanlessEq, SpanlessHash};
37 pub type MethodArgs = HirVec<P<Expr>>;
39 /// Produce a nested chain of if-lets and ifs from the patterns:
54 /// if let Some(y) = x {
56 /// if let Some(z) = y {
63 macro_rules! if_let_chain {
64 ([let $pat:pat = $expr:expr, $($tt:tt)+], $block:block) => {
66 if_let_chain!{ [$($tt)+], $block }
69 ([let $pat:pat = $expr:expr], $block:block) => {
74 ([let $pat:pat = $expr:expr,], $block:block) => {
79 ([$expr:expr, $($tt:tt)+], $block:block) => {
81 if_let_chain!{ [$($tt)+], $block }
84 ([$expr:expr], $block:block) => {
89 ([$expr:expr,], $block:block) => {
98 /// Returns true if the two spans come from differing expansions (i.e. one is
99 /// from a macro and one
101 pub fn differing_macro_contexts(lhs: Span, rhs: Span) -> bool {
102 rhs.ctxt() != lhs.ctxt()
105 pub fn in_constant(cx: &LateContext, id: NodeId) -> bool {
106 let parent_id = cx.tcx.hir.get_parent(id);
107 match MirSource::from_node(cx.tcx, parent_id) {
108 MirSource::GeneratorDrop(_) | MirSource::Fn(_) => false,
109 MirSource::Const(_) | MirSource::Static(..) | MirSource::Promoted(..) => true,
113 /// Returns true if this `expn_info` was expanded by any macro.
114 pub fn in_macro(span: Span) -> bool {
115 span.ctxt().outer().expn_info().map_or(false, |info| {
116 match info.callee.format {
117 // don't treat range expressions desugared to structs as "in_macro"
118 ExpnFormat::CompilerDesugaring(kind) => kind != CompilerDesugaringKind::DotFill,
124 /// Returns true if the macro that expanded the crate was outside of the
125 /// current crate or was a
127 pub fn in_external_macro<'a, T: LintContext<'a>>(cx: &T, span: Span) -> bool {
128 /// Invokes `in_macro` with the expansion info of the given span slightly
129 /// heavy, try to use
130 /// this after other checks have already happened.
131 fn in_macro_ext<'a, T: LintContext<'a>>(cx: &T, info: &ExpnInfo) -> bool {
132 // no ExpnInfo = no macro
133 if let ExpnFormat::MacroAttribute(..) = info.callee.format {
134 // these are all plugins
137 // no span for the callee = external macro
138 info.callee.span.map_or(true, |span| {
139 // no snippet = external macro or compiler-builtin expansion
142 .span_to_snippet(span)
144 .map_or(true, |code| !code.starts_with("macro_rules"))
151 .map_or(false, |info| in_macro_ext(cx, &info))
154 /// Check if a `DefId`'s path matches the given absolute type path usage.
158 /// match_def_path(cx.tcx, id, &["core", "option", "Option"])
161 /// See also the `paths` module.
162 pub fn match_def_path(tcx: TyCtxt, def_id: DefId, path: &[&str]) -> bool {
165 struct AbsolutePathBuffer {
166 names: Vec<symbol::InternedString>,
169 impl ty::item_path::ItemPathBuffer for AbsolutePathBuffer {
170 fn root_mode(&self) -> &ty::item_path::RootMode {
171 const ABSOLUTE: &'static ty::item_path::RootMode = &ty::item_path::RootMode::Absolute;
175 fn push(&mut self, text: &str) {
176 self.names.push(symbol::Symbol::intern(text).as_str());
180 let mut apb = AbsolutePathBuffer { names: vec![] };
182 tcx.push_item_path(&mut apb, def_id);
184 apb.names.len() == path.len() &&
188 .all(|(a, &b)| *a == *b)
191 /// Check if type is struct, enum or union type with given def path.
192 pub fn match_type(cx: &LateContext, ty: Ty, path: &[&str]) -> bool {
194 ty::TyAdt(adt, _) => match_def_path(cx.tcx, adt.did, path),
199 /// Check if the method call given in `expr` belongs to given type.
200 pub fn match_impl_method(cx: &LateContext, expr: &Expr, path: &[&str]) -> bool {
201 let method_call = cx.tables.type_dependent_defs()[expr.hir_id];
202 let trt_id = cx.tcx.impl_of_method(method_call.def_id());
203 if let Some(trt_id) = trt_id {
204 match_def_path(cx.tcx, trt_id, path)
210 /// Check if the method call given in `expr` belongs to given trait.
211 pub fn match_trait_method(cx: &LateContext, expr: &Expr, path: &[&str]) -> bool {
212 let method_call = cx.tables.type_dependent_defs()[expr.hir_id];
213 let trt_id = cx.tcx.trait_of_item(method_call.def_id());
214 if let Some(trt_id) = trt_id {
215 match_def_path(cx.tcx, trt_id, path)
221 /// Check if an expression references a variable of the given name.
222 pub fn match_var(expr: &Expr, var: Name) -> bool {
223 if let ExprPath(QPath::Resolved(None, ref path)) = expr.node {
224 if path.segments.len() == 1 && path.segments[0].name == var {
232 pub fn last_path_segment(path: &QPath) -> &PathSegment {
234 QPath::Resolved(_, ref path) => path.segments
236 .expect("A path must have at least one segment"),
237 QPath::TypeRelative(_, ref seg) => seg,
241 pub fn single_segment_path(path: &QPath) -> Option<&PathSegment> {
243 QPath::Resolved(_, ref path) if path.segments.len() == 1 => Some(&path.segments[0]),
244 QPath::Resolved(..) => None,
245 QPath::TypeRelative(_, ref seg) => Some(seg),
249 /// Match a `Path` against a slice of segment string literals.
253 /// match_qpath(path, &["std", "rt", "begin_unwind"])
255 pub fn match_qpath(path: &QPath, segments: &[&str]) -> bool {
257 QPath::Resolved(_, ref path) => match_path(path, segments),
258 QPath::TypeRelative(ref ty, ref segment) => match ty.node {
259 TyPath(ref inner_path) => {
260 !segments.is_empty() && match_qpath(inner_path, &segments[..(segments.len() - 1)]) &&
261 segment.name == segments[segments.len() - 1]
268 pub fn match_path(path: &Path, segments: &[&str]) -> bool {
272 .zip(segments.iter().rev())
273 .all(|(a, b)| a.name == *b)
276 /// Match a `Path` against a slice of segment string literals, e.g.
280 /// match_qpath(path, &["std", "rt", "begin_unwind"])
282 pub fn match_path_ast(path: &ast::Path, segments: &[&str]) -> bool {
286 .zip(segments.iter().rev())
287 .all(|(a, b)| a.identifier.name == *b)
290 /// Get the definition associated to a path.
291 pub fn path_to_def(cx: &LateContext, path: &[&str]) -> Option<def::Def> {
293 let crates = cx.tcx.crates();
296 .find(|&&krate| cx.tcx.crate_name(krate) == path[0]);
297 if let Some(krate) = krate {
300 index: CRATE_DEF_INDEX,
302 let mut items = cx.tcx.item_children(krate);
303 let mut path_it = path.iter().skip(1).peekable();
306 let segment = match path_it.next() {
307 Some(segment) => segment,
311 for item in mem::replace(&mut items, Rc::new(vec![])).iter() {
312 if item.ident.name == *segment {
313 if path_it.peek().is_none() {
314 return Some(item.def);
317 items = cx.tcx.item_children(item.def.def_id());
327 pub fn const_to_u64(c: &ty::Const) -> u64 {
328 c.val.to_const_int().expect("eddyb says this works").to_u64().expect("see previous expect")
331 /// Convenience function to get the `DefId` of a trait by path.
332 pub fn get_trait_def_id(cx: &LateContext, path: &[&str]) -> Option<DefId> {
333 let def = match path_to_def(cx, path) {
339 def::Def::Trait(trait_id) => Some(trait_id),
344 /// Check whether a type implements a trait.
345 /// See also `get_trait_def_id`.
346 pub fn implements_trait<'a, 'tcx>(
347 cx: &LateContext<'a, 'tcx>,
350 ty_params: &[Ty<'tcx>],
352 let ty = cx.tcx.erase_regions(&ty);
355 .predicate_for_trait_def(cx.param_env, traits::ObligationCause::dummy(), trait_id, 0, ty, ty_params);
356 cx.tcx.infer_ctxt().enter(|infcx| {
357 traits::SelectionContext::new(&infcx).evaluate_obligation_conservatively(&obligation)
361 /// Check whether this type implements Drop.
362 pub fn has_drop(cx: &LateContext, expr: &Expr) -> bool {
363 let struct_ty = cx.tables.expr_ty(expr);
364 match struct_ty.ty_adt_def() {
365 Some(def) => def.has_dtor(cx.tcx),
370 /// Resolve the definition of a node from its `HirId`.
371 pub fn resolve_node(cx: &LateContext, qpath: &QPath, id: HirId) -> def::Def {
372 cx.tables.qpath_def(qpath, id)
375 /// Match an `Expr` against a chain of methods, and return the matched `Expr`s.
377 /// For example, if `expr` represents the `.baz()` in `foo.bar().baz()`,
378 /// `matched_method_chain(expr, &["bar", "baz"])` will return a `Vec`
379 /// containing the `Expr`s for
380 /// `.bar()` and `.baz()`
381 pub fn method_chain_args<'a>(expr: &'a Expr, methods: &[&str]) -> Option<Vec<&'a [Expr]>> {
382 let mut current = expr;
383 let mut matched = Vec::with_capacity(methods.len());
384 for method_name in methods.iter().rev() {
385 // method chains are stored last -> first
386 if let ExprMethodCall(ref path, _, ref args) = current.node {
387 if path.name == *method_name {
388 if args.iter().any(|e| in_macro(e.span)) {
391 matched.push(&**args); // build up `matched` backwards
392 current = &args[0] // go to parent expression
400 matched.reverse(); // reverse `matched`, so that it is in the same order as `methods`
405 /// Get the name of the item the expression is in, if available.
406 pub fn get_item_name(cx: &LateContext, expr: &Expr) -> Option<Name> {
407 let parent_id = cx.tcx.hir.get_parent(expr.id);
408 match cx.tcx.hir.find(parent_id) {
409 Some(Node::NodeItem(&Item { ref name, .. })) |
410 Some(Node::NodeTraitItem(&TraitItem { ref name, .. })) |
411 Some(Node::NodeImplItem(&ImplItem { ref name, .. })) => Some(*name),
416 /// Get the name of a `Pat`, if any
417 pub fn get_pat_name(pat: &Pat) -> Option<Name> {
419 PatKind::Binding(_, _, ref spname, _) => Some(spname.node),
420 PatKind::Path(ref qpath) => single_segment_path(qpath).map(|ps| ps.name),
421 PatKind::Box(ref p) | PatKind::Ref(ref p, _) => get_pat_name(&*p),
426 struct ContainsName {
431 impl<'tcx> Visitor<'tcx> for ContainsName {
432 fn visit_name(&mut self, _: Span, name: Name) {
433 if self.name == name {
437 fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'tcx> {
438 NestedVisitorMap::None
442 /// check if an `Expr` contains a certain name
443 pub fn contains_name(name: Name, expr: &Expr) -> bool {
444 let mut cn = ContainsName {
453 /// Convert a span to a code snippet if available, otherwise use default.
457 /// snippet(cx, expr.span, "..")
459 pub fn snippet<'a, 'b, T: LintContext<'b>>(cx: &T, span: Span, default: &'a str) -> Cow<'a, str> {
460 snippet_opt(cx, span).map_or_else(|| Cow::Borrowed(default), From::from)
463 /// Convert a span to a code snippet. Returns `None` if not available.
464 pub fn snippet_opt<'a, T: LintContext<'a>>(cx: &T, span: Span) -> Option<String> {
465 cx.sess().codemap().span_to_snippet(span).ok()
468 /// Convert a span (from a block) to a code snippet if available, otherwise use
470 /// This trims the code of indentation, except for the first line. Use it for
471 /// blocks or block-like
472 /// things which need to be printed as such.
476 /// snippet(cx, expr.span, "..")
478 pub fn snippet_block<'a, 'b, T: LintContext<'b>>(cx: &T, span: Span, default: &'a str) -> Cow<'a, str> {
479 let snip = snippet(cx, span, default);
480 trim_multiline(snip, true)
483 /// Like `snippet_block`, but add braces if the expr is not an `ExprBlock`.
484 /// Also takes an `Option<String>` which can be put inside the braces.
485 pub fn expr_block<'a, 'b, T: LintContext<'b>>(
488 option: Option<String>,
491 let code = snippet_block(cx, expr.span, default);
492 let string = option.unwrap_or_default();
493 if let ExprBlock(_) = expr.node {
494 Cow::Owned(format!("{}{}", code, string))
495 } else if string.is_empty() {
496 Cow::Owned(format!("{{ {} }}", code))
498 Cow::Owned(format!("{{\n{};\n{}\n}}", code, string))
502 /// Trim indentation from a multiline string with possibility of ignoring the
504 pub fn trim_multiline(s: Cow<str>, ignore_first: bool) -> Cow<str> {
505 let s_space = trim_multiline_inner(s, ignore_first, ' ');
506 let s_tab = trim_multiline_inner(s_space, ignore_first, '\t');
507 trim_multiline_inner(s_tab, ignore_first, ' ')
510 fn trim_multiline_inner(s: Cow<str>, ignore_first: bool, ch: char) -> Cow<str> {
512 .skip(ignore_first as usize)
517 // ignore empty lines
520 .find(|&(_, x)| x != ch)
521 .unwrap_or((l.len(), ch))
532 .map(|(i, l)| if (ignore_first && i == 0) || l.is_empty() {
545 /// Get a parent expressions if any – this is useful to constrain a lint.
546 pub fn get_parent_expr<'c>(cx: &'c LateContext, e: &Expr) -> Option<&'c Expr> {
547 let map = &cx.tcx.hir;
548 let node_id: NodeId = e.id;
549 let parent_id: NodeId = map.get_parent_node(node_id);
550 if node_id == parent_id {
554 .and_then(|node| if let Node::NodeExpr(parent) = node {
561 pub fn get_enclosing_block<'a, 'tcx: 'a>(cx: &LateContext<'a, 'tcx>, node: NodeId) -> Option<&'tcx Block> {
562 let map = &cx.tcx.hir;
563 let enclosing_node = map.get_enclosing_scope(node)
564 .and_then(|enclosing_id| map.find(enclosing_id));
565 if let Some(node) = enclosing_node {
567 Node::NodeBlock(block) => Some(block),
568 Node::NodeItem(&Item {
569 node: ItemFn(_, _, _, _, _, eid),
571 }) => match cx.tcx.hir.body(eid).value.node {
572 ExprBlock(ref block) => Some(block),
582 pub struct DiagnosticWrapper<'a>(pub DiagnosticBuilder<'a>);
584 impl<'a> Drop for DiagnosticWrapper<'a> {
590 impl<'a> DiagnosticWrapper<'a> {
591 fn docs_link(&mut self, lint: &'static Lint) {
592 if env::var("CLIPPY_DISABLE_DOCS_LINKS").is_err() {
593 self.0.help(&format!(
594 "for further information visit https://rust-lang-nursery.github.io/rust-clippy/v{}/index.html#{}",
595 env!("CARGO_PKG_VERSION"),
602 pub fn span_lint<'a, T: LintContext<'a>>(cx: &T, lint: &'static Lint, sp: Span, msg: &str) {
603 DiagnosticWrapper(cx.struct_span_lint(lint, sp, msg)).docs_link(lint);
606 pub fn span_help_and_lint<'a, 'tcx: 'a, T: LintContext<'tcx>>(
613 let mut db = DiagnosticWrapper(cx.struct_span_lint(lint, span, msg));
618 pub fn span_note_and_lint<'a, 'tcx: 'a, T: LintContext<'tcx>>(
626 let mut db = DiagnosticWrapper(cx.struct_span_lint(lint, span, msg));
627 if note_span == span {
630 db.0.span_note(note_span, note);
635 pub fn span_lint_and_then<'a, 'tcx: 'a, T: LintContext<'tcx>, F>(
642 F: for<'b> FnOnce(&mut DiagnosticBuilder<'b>),
644 let mut db = DiagnosticWrapper(cx.struct_span_lint(lint, sp, msg));
649 pub fn span_lint_and_sugg<'a, 'tcx: 'a, T: LintContext<'tcx>>(
657 span_lint_and_then(cx, lint, sp, msg, |db| { db.span_suggestion(sp, help, sugg); });
660 /// Create a suggestion made from several `span → replacement`.
662 /// Note: in the JSON format (used by `compiletest_rs`), the help message will
664 /// replacement. In human-readable format though, it only appears once before
665 /// the whole suggestion.
666 pub fn multispan_sugg(db: &mut DiagnosticBuilder, help_msg: String, sugg: Vec<(Span, String)>) {
667 let sugg = rustc_errors::CodeSuggestion {
668 substitution_parts: sugg.into_iter()
670 rustc_errors::Substitution {
672 substitutions: vec![sub],
677 show_code_when_inline: true,
679 db.suggestions.push(sugg);
682 /// Return the base type for HIR references and pointers.
683 pub fn walk_ptrs_hir_ty(ty: &hir::Ty) -> &hir::Ty {
686 TyRptr(_, ref mut_ty) => walk_ptrs_hir_ty(&mut_ty.ty),
691 /// Return the base type for references and raw pointers.
692 pub fn walk_ptrs_ty(ty: Ty) -> Ty {
694 ty::TyRef(_, ref tm) => walk_ptrs_ty(tm.ty),
699 /// Return the base type for references and raw pointers, and count reference
701 pub fn walk_ptrs_ty_depth(ty: Ty) -> (Ty, usize) {
702 fn inner(ty: Ty, depth: usize) -> (Ty, usize) {
704 ty::TyRef(_, ref tm) => inner(tm.ty, depth + 1),
711 /// Check whether the given expression is a constant literal of the given value.
712 pub fn is_integer_literal(expr: &Expr, value: u128) -> bool {
713 // FIXME: use constant folding
714 if let ExprLit(ref spanned) = expr.node {
715 if let LitKind::Int(v, _) = spanned.node {
722 pub fn is_adjusted(cx: &LateContext, e: &Expr) -> bool {
723 cx.tables.adjustments().get(e.hir_id).is_some()
726 pub struct LimitStack {
730 impl Drop for LimitStack {
732 assert_eq!(self.stack.len(), 1);
737 pub fn new(limit: u64) -> Self {
738 Self { stack: vec![limit] }
740 pub fn limit(&self) -> u64 {
743 .expect("there should always be a value in the stack")
745 pub fn push_attrs(&mut self, sess: &Session, attrs: &[ast::Attribute], name: &'static str) {
746 let stack = &mut self.stack;
747 parse_attrs(sess, attrs, name, |val| stack.push(val));
749 pub fn pop_attrs(&mut self, sess: &Session, attrs: &[ast::Attribute], name: &'static str) {
750 let stack = &mut self.stack;
751 parse_attrs(sess, attrs, name, |val| assert_eq!(stack.pop(), Some(val)));
755 fn parse_attrs<F: FnMut(u64)>(sess: &Session, attrs: &[ast::Attribute], name: &'static str, mut f: F) {
757 if attr.is_sugared_doc {
760 if let Some(ref value) = attr.value_str() {
761 if attr.name().map_or(false, |n| n == name) {
762 if let Ok(value) = FromStr::from_str(&value.as_str()) {
763 attr::mark_used(attr);
766 sess.span_err(attr.span, "not a number");
773 /// Return the pre-expansion span if is this comes from an expansion of the
775 /// See also `is_direct_expn_of`.
776 pub fn is_expn_of(mut span: Span, name: &str) -> Option<Span> {
778 let span_name_span = span.ctxt()
781 .map(|ei| (ei.callee.name(), ei.call_site));
783 match span_name_span {
784 Some((mac_name, new_span)) if mac_name == name => return Some(new_span),
786 Some((_, new_span)) => span = new_span,
791 /// Return the pre-expansion span if is this directly comes from an expansion
792 /// of the macro `name`.
793 /// The difference with `is_expn_of` is that in
797 /// `42` is considered expanded from `foo!` and `bar!` by `is_expn_of` but only
799 /// `is_direct_expn_of`.
800 pub fn is_direct_expn_of(span: Span, name: &str) -> Option<Span> {
801 let span_name_span = span.ctxt()
804 .map(|ei| (ei.callee.name(), ei.call_site));
806 match span_name_span {
807 Some((mac_name, new_span)) if mac_name == name => Some(new_span),
812 /// Return the index of the character after the first camel-case component of
814 pub fn camel_case_until(s: &str) -> usize {
815 let mut iter = s.char_indices();
816 if let Some((_, first)) = iter.next() {
817 if !first.is_uppercase() {
827 if c.is_lowercase() {
832 } else if c.is_uppercase() {
835 } else if !c.is_lowercase() {
846 /// Return index of the last camel-case component of `s`.
847 pub fn camel_case_from(s: &str) -> usize {
848 let mut iter = s.char_indices().rev();
849 if let Some((_, first)) = iter.next() {
850 if !first.is_lowercase() {
857 let mut last_i = s.len();
860 if c.is_uppercase() {
863 } else if !c.is_lowercase() {
866 } else if c.is_lowercase() {
875 /// Convenience function to get the return type of a function
876 pub fn return_ty<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, fn_item: NodeId) -> Ty<'tcx> {
877 let fn_def_id = cx.tcx.hir.local_def_id(fn_item);
878 let ret_ty = cx.tcx.fn_sig(fn_def_id).output();
879 cx.tcx.erase_late_bound_regions(&ret_ty)
882 /// Check if two types are the same.
883 // FIXME: this works correctly for lifetimes bounds (`for <'a> Foo<'a>` == `for
885 // not for type parameters.
886 pub fn same_tys<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, a: Ty<'tcx>, b: Ty<'tcx>) -> bool {
889 .enter(|infcx| infcx.can_eq(cx.param_env, a, b).is_ok())
892 /// Return whether the given type is an `unsafe` function.
893 pub fn type_is_unsafe_function<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, ty: Ty<'tcx>) -> bool {
895 ty::TyFnDef(..) | ty::TyFnPtr(_) => ty.fn_sig(cx.tcx).unsafety() == Unsafety::Unsafe,
900 pub fn is_copy<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, ty: Ty<'tcx>) -> bool {
901 !ty.moves_by_default(cx.tcx.global_tcx(), cx.param_env, DUMMY_SP)
904 /// Return whether a pattern is refutable.
905 pub fn is_refutable(cx: &LateContext, pat: &Pat) -> bool {
906 fn is_enum_variant(cx: &LateContext, qpath: &QPath, id: HirId) -> bool {
908 cx.tables.qpath_def(qpath, id),
909 def::Def::Variant(..) | def::Def::VariantCtor(..)
913 fn are_refutable<'a, I: Iterator<Item = &'a Pat>>(cx: &LateContext, mut i: I) -> bool {
914 i.any(|pat| is_refutable(cx, pat))
918 PatKind::Binding(..) | PatKind::Wild => false,
919 PatKind::Box(ref pat) | PatKind::Ref(ref pat, _) => is_refutable(cx, pat),
920 PatKind::Lit(..) | PatKind::Range(..) => true,
921 PatKind::Path(ref qpath) => is_enum_variant(cx, qpath, pat.hir_id),
922 PatKind::Tuple(ref pats, _) => are_refutable(cx, pats.iter().map(|pat| &**pat)),
923 PatKind::Struct(ref qpath, ref fields, _) => if is_enum_variant(cx, qpath, pat.hir_id) {
926 are_refutable(cx, fields.iter().map(|field| &*field.node.pat))
928 PatKind::TupleStruct(ref qpath, ref pats, _) => if is_enum_variant(cx, qpath, pat.hir_id) {
931 are_refutable(cx, pats.iter().map(|pat| &**pat))
933 PatKind::Slice(ref head, ref middle, ref tail) => are_refutable(
943 /// Checks for the `#[automatically_derived]` attribute all `#[derive]`d
944 /// implementations have.
945 pub fn is_automatically_derived(attrs: &[ast::Attribute]) -> bool {
946 attr::contains_name(attrs, "automatically_derived")
949 /// Remove blocks around an expression.
951 /// Ie. `x`, `{ x }` and `{{{{ x }}}}` all give `x`. `{ x; y }` and `{}` return
953 pub fn remove_blocks(expr: &Expr) -> &Expr {
954 if let ExprBlock(ref block) = expr.node {
955 if block.stmts.is_empty() {
956 if let Some(ref expr) = block.expr {
969 pub fn opt_def_id(def: Def) -> Option<DefId> {
975 Def::VariantCtor(id, ..) |
978 Def::AssociatedTy(id) |
981 Def::StructCtor(id, ..) |
986 Def::AssociatedConst(id) |
988 Def::GlobalAsm(id) => Some(id),
990 Def::Upvar(..) | Def::Local(_) | Def::Label(..) | Def::PrimTy(..) | Def::SelfTy(..) | Def::Err => None,
994 pub fn is_self(slf: &Arg) -> bool {
995 if let PatKind::Binding(_, _, name, _) = slf.pat.node {
996 name.node == keywords::SelfValue.name()
1002 pub fn is_self_ty(slf: &hir::Ty) -> bool {
1004 let TyPath(ref qp) = slf.node,
1005 let QPath::Resolved(None, ref path) = *qp,
1006 let Def::SelfTy(..) = path.def,
1013 pub fn iter_input_pats<'tcx>(decl: &FnDecl, body: &'tcx Body) -> impl Iterator<Item = &'tcx Arg> {
1014 (0..decl.inputs.len()).map(move |i| &body.arguments[i])
1017 /// Check if a given expression is a match expression
1018 /// expanded from `?` operator or `try` macro.
1019 pub fn is_try(expr: &Expr) -> Option<&Expr> {
1020 fn is_ok(arm: &Arm) -> bool {
1022 let PatKind::TupleStruct(ref path, ref pat, None) = arm.pats[0].node,
1023 match_qpath(path, &paths::RESULT_OK[1..]),
1024 let PatKind::Binding(_, defid, _, None) = pat[0].node,
1025 let ExprPath(QPath::Resolved(None, ref path)) = arm.body.node,
1026 let Def::Local(lid) = path.def,
1034 fn is_err(arm: &Arm) -> bool {
1035 if let PatKind::TupleStruct(ref path, _, _) = arm.pats[0].node {
1036 match_qpath(path, &paths::RESULT_ERR[1..])
1042 if let ExprMatch(_, ref arms, ref source) = expr.node {
1043 // desugared from a `?` operator
1044 if let MatchSource::TryDesugar = *source {
1050 arms[0].pats.len() == 1 && arms[0].guard.is_none(),
1051 arms[1].pats.len() == 1 && arms[1].guard.is_none(),
1052 (is_ok(&arms[0]) && is_err(&arms[1])) ||
1053 (is_ok(&arms[1]) && is_err(&arms[0])),
1062 pub fn type_size<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, ty: Ty<'tcx>) -> Option<u64> {
1063 ty.layout(cx.tcx, cx.param_env)
1065 .map(|layout| layout.size(cx.tcx).bytes())
1068 /// Returns true if the lint is allowed in the current context
1070 /// Useful for skipping long running code when it's unnecessary
1071 pub fn is_allowed(cx: &LateContext, lint: &'static Lint, id: NodeId) -> bool {
1072 cx.tcx.lint_level_at_node(lint, id).0 == Level::Allow