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::{LintContext, Level, LateContext, Lint};
9 use rustc::session::Session;
11 use rustc::ty::{self, TyCtxt, Ty};
12 use rustc::mir::transform::MirSource;
17 use std::str::FromStr;
18 use syntax::ast::{self, LitKind};
20 use syntax::codemap::{CompilerDesugaringKind, ExpnFormat, ExpnInfo, Span, DUMMY_SP};
21 use syntax::errors::DiagnosticBuilder;
23 use syntax::symbol::keywords;
32 pub mod internal_lints;
34 pub use self::hir_utils::{SpanlessEq, SpanlessHash};
36 pub type MethodArgs = HirVec<P<Expr>>;
38 /// Produce a nested chain of if-lets and ifs from the patterns:
53 /// if let Some(y) = x {
55 /// if let Some(z) = y {
62 macro_rules! if_let_chain {
63 ([let $pat:pat = $expr:expr, $($tt:tt)+], $block:block) => {
65 if_let_chain!{ [$($tt)+], $block }
68 ([let $pat:pat = $expr:expr], $block:block) => {
73 ([let $pat:pat = $expr:expr,], $block:block) => {
78 ([$expr:expr, $($tt:tt)+], $block:block) => {
80 if_let_chain!{ [$($tt)+], $block }
83 ([$expr:expr], $block:block) => {
88 ([$expr:expr,], $block:block) => {
97 /// Returns true if the two spans come from differing expansions (i.e. one is
98 /// from a macro and one
100 pub fn differing_macro_contexts(lhs: Span, rhs: Span) -> bool {
104 pub fn in_constant(cx: &LateContext, id: NodeId) -> bool {
105 let parent_id = cx.tcx.hir.get_parent(id);
106 match MirSource::from_node(cx.tcx, parent_id) {
107 MirSource::Fn(_) => false,
108 MirSource::Const(_) |
109 MirSource::Static(..) |
110 MirSource::Promoted(..) => true,
114 /// Returns true if this `expn_info` was expanded by any macro.
115 pub fn in_macro(span: Span) -> bool {
116 span.ctxt.outer().expn_info().map_or(false, |info| {
117 match info.callee.format {// 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
140 cx.sess().codemap().span_to_snippet(span).ok().map_or(
143 !code.starts_with("macro_rules")
149 span.ctxt.outer().expn_info().map_or(false, |info| {
150 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() &&
185 apb.names.into_iter().zip(path.iter()).all(
190 /// Check if type is struct, enum or union type with given def path.
191 pub fn match_type(cx: &LateContext, ty: Ty, path: &[&str]) -> bool {
193 ty::TyAdt(adt, _) => match_def_path(cx.tcx, adt.did, path),
198 /// Check if the method call given in `expr` belongs to given type.
199 pub fn match_impl_method(cx: &LateContext, expr: &Expr, path: &[&str]) -> bool {
200 let method_call = cx.tables.type_dependent_defs()[expr.hir_id];
201 let trt_id = cx.tcx.impl_of_method(method_call.def_id());
202 if let Some(trt_id) = trt_id {
203 match_def_path(cx.tcx, trt_id, path)
209 /// Check if the method call given in `expr` belongs to given trait.
210 pub fn match_trait_method(cx: &LateContext, expr: &Expr, path: &[&str]) -> bool {
211 let method_call = cx.tables.type_dependent_defs()[expr.hir_id];
212 let trt_id = cx.tcx.trait_of_item(method_call.def_id());
213 if let Some(trt_id) = trt_id {
214 match_def_path(cx.tcx, trt_id, path)
220 pub fn last_path_segment(path: &QPath) -> &PathSegment {
222 QPath::Resolved(_, ref path) => {
223 path.segments.last().expect(
224 "A path must have at least one segment",
227 QPath::TypeRelative(_, ref seg) => seg,
231 pub fn single_segment_path(path: &QPath) -> Option<&PathSegment> {
233 QPath::Resolved(_, ref path) if path.segments.len() == 1 => Some(&path.segments[0]),
234 QPath::Resolved(..) => None,
235 QPath::TypeRelative(_, ref seg) => Some(seg),
239 /// Match a `Path` against a slice of segment string literals.
243 /// match_path(path, &["std", "rt", "begin_unwind"])
245 pub fn match_path(path: &QPath, segments: &[&str]) -> bool {
247 QPath::Resolved(_, ref path) => match_path_old(path, segments),
248 QPath::TypeRelative(ref ty, ref segment) => {
250 TyPath(ref inner_path) => {
251 !segments.is_empty() && match_path(inner_path, &segments[..(segments.len() - 1)]) &&
252 segment.name == segments[segments.len() - 1]
260 pub fn match_path_old(path: &Path, segments: &[&str]) -> bool {
261 path.segments.iter().rev().zip(segments.iter().rev()).all(
262 |(a, b)| a.name == *b,
266 /// Match a `Path` against a slice of segment string literals, e.g.
270 /// match_path(path, &["std", "rt", "begin_unwind"])
272 pub fn match_path_ast(path: &ast::Path, segments: &[&str]) -> bool {
273 path.segments.iter().rev().zip(segments.iter().rev()).all(
274 |(a, b)| a.identifier.name == *b,
278 /// Get the definition associated to a path.
279 pub fn path_to_def(cx: &LateContext, path: &[&str]) -> Option<def::Def> {
280 let cstore = &cx.tcx.sess.cstore;
282 let crates = cstore.crates();
283 let krate = crates.iter().find(
284 |&&krate| cstore.crate_name(krate) == path[0],
286 if let Some(krate) = krate {
289 index: CRATE_DEF_INDEX,
291 let mut items = cstore.item_children(krate, cx.tcx.sess);
292 let mut path_it = path.iter().skip(1).peekable();
295 let segment = match path_it.next() {
296 Some(segment) => segment,
300 for item in &mem::replace(&mut items, vec![]) {
301 if item.ident.name == *segment {
302 if path_it.peek().is_none() {
303 return Some(item.def);
306 items = cstore.item_children(item.def.def_id(), cx.tcx.sess);
316 /// Convenience function to get the `DefId` of a trait by path.
317 pub fn get_trait_def_id(cx: &LateContext, path: &[&str]) -> Option<DefId> {
318 let def = match path_to_def(cx, path) {
324 def::Def::Trait(trait_id) => Some(trait_id),
329 /// Check whether a type implements a trait.
330 /// See also `get_trait_def_id`.
331 pub fn implements_trait<'a, 'tcx>(
332 cx: &LateContext<'a, 'tcx>,
335 ty_params: &[Ty<'tcx>],
337 let ty = cx.tcx.erase_regions(&ty);
338 let obligation = cx.tcx.predicate_for_trait_def(
340 traits::ObligationCause::dummy(),
346 cx.tcx.infer_ctxt().enter(|infcx| {
347 traits::SelectionContext::new(&infcx).evaluate_obligation_conservatively(&obligation)
351 /// Resolve the definition of a node from its `HirId`.
352 pub fn resolve_node(cx: &LateContext, qpath: &QPath, id: HirId) -> def::Def {
353 cx.tables.qpath_def(qpath, id)
356 /// Match an `Expr` against a chain of methods, and return the matched `Expr`s.
358 /// For example, if `expr` represents the `.baz()` in `foo.bar().baz()`,
359 /// `matched_method_chain(expr, &["bar", "baz"])` will return a `Vec`
360 /// containing the `Expr`s for
361 /// `.bar()` and `.baz()`
362 pub fn method_chain_args<'a>(expr: &'a Expr, methods: &[&str]) -> Option<Vec<&'a [Expr]>> {
363 let mut current = expr;
364 let mut matched = Vec::with_capacity(methods.len());
365 for method_name in methods.iter().rev() {
366 // method chains are stored last -> first
367 if let ExprMethodCall(ref path, _, ref args) = current.node {
368 if path.name == *method_name {
369 if args.iter().any(|e| in_macro(e.span)) {
372 matched.push(&**args); // build up `matched` backwards
373 current = &args[0] // go to parent expression
381 matched.reverse(); // reverse `matched`, so that it is in the same order as `methods`
386 /// Get the name of the item the expression is in, if available.
387 pub fn get_item_name(cx: &LateContext, expr: &Expr) -> Option<Name> {
388 let parent_id = cx.tcx.hir.get_parent(expr.id);
389 match cx.tcx.hir.find(parent_id) {
390 Some(Node::NodeItem(&Item { ref name, .. })) |
391 Some(Node::NodeTraitItem(&TraitItem { ref name, .. })) |
392 Some(Node::NodeImplItem(&ImplItem { ref name, .. })) => Some(*name),
397 struct ContainsName {
402 impl<'tcx> Visitor<'tcx> for ContainsName {
403 fn visit_name(&mut self, _: Span, name: Name) {
404 if self.name == name {
408 fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'tcx> {
409 NestedVisitorMap::None
413 /// check if an `Expr` contains a certain name
414 pub fn contains_name(name: Name, expr: &Expr) -> bool {
415 let mut cn = ContainsName {
424 /// Convert a span to a code snippet if available, otherwise use default.
428 /// snippet(cx, expr.span, "..")
430 pub fn snippet<'a, 'b, T: LintContext<'b>>(cx: &T, span: Span, default: &'a str) -> Cow<'a, str> {
431 snippet_opt(cx, span).map_or_else(|| Cow::Borrowed(default), From::from)
434 /// Convert a span to a code snippet. Returns `None` if not available.
435 pub fn snippet_opt<'a, T: LintContext<'a>>(cx: &T, span: Span) -> Option<String> {
436 cx.sess().codemap().span_to_snippet(span).ok()
439 /// Convert a span (from a block) to a code snippet if available, otherwise use
441 /// This trims the code of indentation, except for the first line. Use it for
442 /// blocks or block-like
443 /// things which need to be printed as such.
447 /// snippet(cx, expr.span, "..")
449 pub fn snippet_block<'a, 'b, T: LintContext<'b>>(cx: &T, span: Span, default: &'a str) -> Cow<'a, str> {
450 let snip = snippet(cx, span, default);
451 trim_multiline(snip, true)
454 /// Like `snippet_block`, but add braces if the expr is not an `ExprBlock`.
455 /// Also takes an `Option<String>` which can be put inside the braces.
456 pub fn expr_block<'a, 'b, T: LintContext<'b>>(
459 option: Option<String>,
462 let code = snippet_block(cx, expr.span, default);
463 let string = option.unwrap_or_default();
464 if let ExprBlock(_) = expr.node {
465 Cow::Owned(format!("{}{}", code, string))
466 } else if string.is_empty() {
467 Cow::Owned(format!("{{ {} }}", code))
469 Cow::Owned(format!("{{\n{};\n{}\n}}", code, string))
473 /// Trim indentation from a multiline string with possibility of ignoring the
475 pub fn trim_multiline(s: Cow<str>, ignore_first: bool) -> Cow<str> {
476 let s_space = trim_multiline_inner(s, ignore_first, ' ');
477 let s_tab = trim_multiline_inner(s_space, ignore_first, '\t');
478 trim_multiline_inner(s_tab, ignore_first, ' ')
481 fn trim_multiline_inner(s: Cow<str>, ignore_first: bool, ch: char) -> Cow<str> {
483 .skip(ignore_first as usize)
488 // ignore empty lines
491 .find(|&(_, x)| x != ch)
492 .unwrap_or((l.len(), ch))
503 .map(|(i, l)| if (ignore_first && i == 0) || l.is_empty() {
516 /// Get a parent expressions if any – this is useful to constrain a lint.
517 pub fn get_parent_expr<'c>(cx: &'c LateContext, e: &Expr) -> Option<&'c Expr> {
518 let map = &cx.tcx.hir;
519 let node_id: NodeId = e.id;
520 let parent_id: NodeId = map.get_parent_node(node_id);
521 if node_id == parent_id {
524 map.find(parent_id).and_then(
525 |node| if let Node::NodeExpr(parent) =
535 pub fn get_enclosing_block<'a, 'tcx: 'a>(cx: &LateContext<'a, 'tcx>, node: NodeId) -> Option<&'tcx Block> {
536 let map = &cx.tcx.hir;
537 let enclosing_node = map.get_enclosing_scope(node).and_then(|enclosing_id| {
538 map.find(enclosing_id)
540 if let Some(node) = enclosing_node {
542 Node::NodeBlock(block) => Some(block),
543 Node::NodeItem(&Item { node: ItemFn(_, _, _, _, _, eid), .. }) => {
544 match cx.tcx.hir.body(eid).value.node {
545 ExprBlock(ref block) => Some(block),
556 pub struct DiagnosticWrapper<'a>(pub DiagnosticBuilder<'a>);
558 impl<'a> Drop for DiagnosticWrapper<'a> {
564 impl<'a> DiagnosticWrapper<'a> {
565 fn wiki_link(&mut self, lint: &'static Lint) {
566 if env::var("CLIPPY_DISABLE_WIKI_LINKS").is_err() {
567 self.0.help(&format!(
568 "for further information visit https://github.com/rust-lang-nursery/rust-clippy/wiki#{}",
575 pub fn span_lint<'a, T: LintContext<'a>>(cx: &T, lint: &'static Lint, sp: Span, msg: &str) {
576 DiagnosticWrapper(cx.struct_span_lint(lint, sp, msg)).wiki_link(lint);
579 pub fn span_help_and_lint<'a, 'tcx: 'a, T: LintContext<'tcx>>(
586 let mut db = DiagnosticWrapper(cx.struct_span_lint(lint, span, msg));
591 pub fn span_note_and_lint<'a, 'tcx: 'a, T: LintContext<'tcx>>(
599 let mut db = DiagnosticWrapper(cx.struct_span_lint(lint, span, msg));
600 if note_span == span {
603 db.0.span_note(note_span, note);
608 pub fn span_lint_and_then<'a, 'tcx: 'a, T: LintContext<'tcx>, F>(
615 F: for<'b> FnOnce(&mut DiagnosticBuilder<'b>),
617 let mut db = DiagnosticWrapper(cx.struct_span_lint(lint, sp, msg));
622 pub fn span_lint_and_sugg<'a, 'tcx: 'a, T: LintContext<'tcx>>(
630 span_lint_and_then(cx, lint, sp, msg, |db| { db.span_suggestion(sp, help, sugg); });
633 /// Create a suggestion made from several `span → replacement`.
635 /// Note: in the JSON format (used by `compiletest_rs`), the help message will
637 /// replacement. In human-readable format though, it only appears once before
638 /// the whole suggestion.
639 pub fn multispan_sugg(db: &mut DiagnosticBuilder, help_msg: String, sugg: Vec<(Span, String)>) {
640 let sugg = rustc_errors::CodeSuggestion {
641 substitution_parts: sugg.into_iter()
643 rustc_errors::Substitution {
645 substitutions: vec![sub],
650 show_code_when_inline: true,
652 db.suggestions.push(sugg);
655 /// Return the base type for references and raw pointers.
656 pub fn walk_ptrs_ty(ty: Ty) -> Ty {
658 ty::TyRef(_, ref tm) => walk_ptrs_ty(tm.ty),
663 /// Return the base type for references and raw pointers, and count reference
665 pub fn walk_ptrs_ty_depth(ty: Ty) -> (Ty, usize) {
666 fn inner(ty: Ty, depth: usize) -> (Ty, usize) {
668 ty::TyRef(_, ref tm) => inner(tm.ty, depth + 1),
675 /// Check whether the given expression is a constant literal of the given value.
676 pub fn is_integer_literal(expr: &Expr, value: u128) -> bool {
677 // FIXME: use constant folding
678 if let ExprLit(ref spanned) = expr.node {
679 if let LitKind::Int(v, _) = spanned.node {
686 pub fn is_adjusted(cx: &LateContext, e: &Expr) -> bool {
687 cx.tables.adjustments().get(e.hir_id).is_some()
690 pub struct LimitStack {
694 impl Drop for LimitStack {
696 assert_eq!(self.stack.len(), 1);
701 pub fn new(limit: u64) -> Self {
702 Self { stack: vec![limit] }
704 pub fn limit(&self) -> u64 {
705 *self.stack.last().expect(
706 "there should always be a value in the stack",
709 pub fn push_attrs(&mut self, sess: &Session, attrs: &[ast::Attribute], name: &'static str) {
710 let stack = &mut self.stack;
711 parse_attrs(sess, attrs, name, |val| stack.push(val));
713 pub fn pop_attrs(&mut self, sess: &Session, attrs: &[ast::Attribute], name: &'static str) {
714 let stack = &mut self.stack;
715 parse_attrs(sess, attrs, name, |val| assert_eq!(stack.pop(), Some(val)));
719 fn parse_attrs<F: FnMut(u64)>(sess: &Session, attrs: &[ast::Attribute], name: &'static str, mut f: F) {
721 if attr.is_sugared_doc {
724 if let Some(ref value) = attr.value_str() {
725 if attr.name().map_or(false, |n| n == name) {
726 if let Ok(value) = FromStr::from_str(&value.as_str()) {
727 attr::mark_used(attr);
730 sess.span_err(attr.span, "not a number");
737 /// Return the pre-expansion span if is this comes from an expansion of the
739 /// See also `is_direct_expn_of`.
740 pub fn is_expn_of(mut span: Span, name: &str) -> Option<Span> {
742 let span_name_span = span.ctxt.outer().expn_info().map(|ei| {
743 (ei.callee.name(), ei.call_site)
746 match span_name_span {
747 Some((mac_name, new_span)) if mac_name == name => return Some(new_span),
749 Some((_, new_span)) => span = new_span,
754 /// Return the pre-expansion span if is this directly comes from an expansion
755 /// of the macro `name`.
756 /// The difference with `is_expn_of` is that in
760 /// `42` is considered expanded from `foo!` and `bar!` by `is_expn_of` but only
762 /// `is_direct_expn_of`.
763 pub fn is_direct_expn_of(span: Span, name: &str) -> Option<Span> {
764 let span_name_span = span.ctxt.outer().expn_info().map(|ei| {
765 (ei.callee.name(), ei.call_site)
768 match span_name_span {
769 Some((mac_name, new_span)) if mac_name == name => Some(new_span),
774 /// Return the index of the character after the first camel-case component of
776 pub fn camel_case_until(s: &str) -> usize {
777 let mut iter = s.char_indices();
778 if let Some((_, first)) = iter.next() {
779 if !first.is_uppercase() {
789 if c.is_lowercase() {
794 } else if c.is_uppercase() {
797 } else if !c.is_lowercase() {
801 if up { last_i } else { s.len() }
804 /// Return index of the last camel-case component of `s`.
805 pub fn camel_case_from(s: &str) -> usize {
806 let mut iter = s.char_indices().rev();
807 if let Some((_, first)) = iter.next() {
808 if !first.is_lowercase() {
815 let mut last_i = s.len();
818 if c.is_uppercase() {
821 } else if !c.is_lowercase() {
824 } else if c.is_lowercase() {
833 /// Convenience function to get the return type of a function
834 pub fn return_ty<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, fn_item: NodeId) -> Ty<'tcx> {
835 let fn_def_id = cx.tcx.hir.local_def_id(fn_item);
836 let ret_ty = cx.tcx.fn_sig(fn_def_id).output();
837 cx.tcx.erase_late_bound_regions(&ret_ty)
840 /// Check if two types are the same.
841 // FIXME: this works correctly for lifetimes bounds (`for <'a> Foo<'a>` == `for
843 // not for type parameters.
844 pub fn same_tys<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, a: Ty<'tcx>, b: Ty<'tcx>) -> bool {
845 cx.tcx.infer_ctxt().enter(|infcx| {
846 infcx.can_eq(cx.param_env, a, b).is_ok()
850 /// Return whether the given type is an `unsafe` function.
851 pub fn type_is_unsafe_function<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, ty: Ty<'tcx>) -> bool {
853 ty::TyFnDef(..) | ty::TyFnPtr(_) => ty.fn_sig(cx.tcx).unsafety() == Unsafety::Unsafe,
858 pub fn is_copy<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, ty: Ty<'tcx>) -> bool {
859 !ty.moves_by_default(cx.tcx.global_tcx(), cx.param_env, DUMMY_SP)
862 /// Return whether a pattern is refutable.
863 pub fn is_refutable(cx: &LateContext, pat: &Pat) -> bool {
864 fn is_enum_variant(cx: &LateContext, qpath: &QPath, id: HirId) -> bool {
866 cx.tables.qpath_def(qpath, id),
867 def::Def::Variant(..) | def::Def::VariantCtor(..)
871 fn are_refutable<'a, I: Iterator<Item = &'a Pat>>(cx: &LateContext, mut i: I) -> bool {
872 i.any(|pat| is_refutable(cx, pat))
876 PatKind::Binding(..) |
877 PatKind::Wild => false,
878 PatKind::Box(ref pat) |
879 PatKind::Ref(ref pat, _) => is_refutable(cx, pat),
881 PatKind::Range(..) => true,
882 PatKind::Path(ref qpath) => is_enum_variant(cx, qpath, pat.hir_id),
883 PatKind::Tuple(ref pats, _) => are_refutable(cx, pats.iter().map(|pat| &**pat)),
884 PatKind::Struct(ref qpath, ref fields, _) => {
885 if is_enum_variant(cx, qpath, pat.hir_id) {
888 are_refutable(cx, fields.iter().map(|field| &*field.node.pat))
891 PatKind::TupleStruct(ref qpath, ref pats, _) => {
892 if is_enum_variant(cx, qpath, pat.hir_id) {
895 are_refutable(cx, pats.iter().map(|pat| &**pat))
898 PatKind::Slice(ref head, ref middle, ref tail) => {
901 head.iter().chain(middle).chain(tail.iter()).map(
909 /// Checks for the `#[automatically_derived]` attribute all `#[derive]`d
910 /// implementations have.
911 pub fn is_automatically_derived(attrs: &[ast::Attribute]) -> bool {
912 attr::contains_name(attrs, "automatically_derived")
915 /// Remove blocks around an expression.
917 /// Ie. `x`, `{ x }` and `{{{{ x }}}}` all give `x`. `{ x; y }` and `{}` return
919 pub fn remove_blocks(expr: &Expr) -> &Expr {
920 if let ExprBlock(ref block) = expr.node {
921 if block.stmts.is_empty() {
922 if let Some(ref expr) = block.expr {
935 pub fn opt_def_id(def: Def) -> Option<DefId> {
941 Def::VariantCtor(id, ..) |
944 Def::AssociatedTy(id) |
947 Def::StructCtor(id, ..) |
952 Def::AssociatedConst(id) |
956 Def::GlobalAsm(id) => Some(id),
958 Def::Label(..) | Def::PrimTy(..) | Def::SelfTy(..) | Def::Err => None,
962 pub fn is_self(slf: &Arg) -> bool {
963 if let PatKind::Binding(_, _, name, _) = slf.pat.node {
964 name.node == keywords::SelfValue.name()
970 pub fn is_self_ty(slf: &hir::Ty) -> bool {
972 let TyPath(ref qp) = slf.node,
973 let QPath::Resolved(None, ref path) = *qp,
974 let Def::SelfTy(..) = path.def,
981 pub fn iter_input_pats<'tcx>(decl: &FnDecl, body: &'tcx Body) -> impl Iterator<Item = &'tcx Arg> {
982 (0..decl.inputs.len()).map(move |i| &body.arguments[i])
985 /// Check if a given expression is a match expression
986 /// expanded from `?` operator or `try` macro.
987 pub fn is_try(expr: &Expr) -> Option<&Expr> {
988 fn is_ok(arm: &Arm) -> bool {
990 let PatKind::TupleStruct(ref path, ref pat, None) = arm.pats[0].node,
991 match_path(path, &paths::RESULT_OK[1..]),
992 let PatKind::Binding(_, defid, _, None) = pat[0].node,
993 let ExprPath(QPath::Resolved(None, ref path)) = arm.body.node,
994 path.def.def_id() == defid,
1001 fn is_err(arm: &Arm) -> bool {
1002 if let PatKind::TupleStruct(ref path, _, _) = arm.pats[0].node {
1003 match_path(path, &paths::RESULT_ERR[1..])
1009 if let ExprMatch(_, ref arms, ref source) = expr.node {
1010 // desugared from a `?` operator
1011 if let MatchSource::TryDesugar = *source {
1017 arms[0].pats.len() == 1 && arms[0].guard.is_none(),
1018 arms[1].pats.len() == 1 && arms[1].guard.is_none(),
1019 (is_ok(&arms[0]) && is_err(&arms[1])) ||
1020 (is_ok(&arms[1]) && is_err(&arms[0])),
1029 pub fn type_size<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, ty: Ty<'tcx>) -> Option<u64> {
1030 ty.layout(cx.tcx, cx.param_env).ok().map(|layout| {
1031 layout.size(cx.tcx).bytes()
1035 /// Returns true if the lint is allowed in the current context
1037 /// Useful for skipping long running code when it's unnecessary
1038 pub fn is_allowed(cx: &LateContext, lint: &'static Lint, id: NodeId) -> bool {
1039 cx.tcx.lint_level_at_node(lint, id).0 == Level::Allow