4 use rustc::hir::def_id::{DefId, CRATE_DEF_INDEX};
5 use rustc::hir::def::Def;
6 use rustc::hir::map::Node;
7 use rustc::lint::{LintContext, Level, LateContext, Lint};
8 use rustc::session::Session;
10 use rustc::ty::{self, TyCtxt, Ty};
11 use rustc::mir::transform::MirSource;
16 use std::str::FromStr;
17 use syntax::ast::{self, LitKind};
19 use syntax::codemap::{ExpnFormat, ExpnInfo, Span, DUMMY_SP};
20 use syntax::errors::DiagnosticBuilder;
22 use syntax::symbol::keywords;
31 pub mod internal_lints;
33 pub use self::hir_utils::{SpanlessEq, SpanlessHash};
35 pub type MethodArgs = HirVec<P<Expr>>;
37 /// Produce a nested chain of if-lets and ifs from the patterns:
52 /// if let Some(y) = x {
54 /// if let Some(z) = y {
61 macro_rules! if_let_chain {
62 ([let $pat:pat = $expr:expr, $($tt:tt)+], $block:block) => {
64 if_let_chain!{ [$($tt)+], $block }
67 ([let $pat:pat = $expr:expr], $block:block) => {
72 ([let $pat:pat = $expr:expr,], $block:block) => {
77 ([$expr:expr, $($tt:tt)+], $block:block) => {
79 if_let_chain!{ [$($tt)+], $block }
82 ([$expr:expr], $block:block) => {
87 ([$expr:expr,], $block:block) => {
96 /// Returns true if the two spans come from differing expansions (i.e. one is
97 /// from a macro and one
99 pub fn differing_macro_contexts(lhs: Span, rhs: Span) -> bool {
103 pub fn in_constant(cx: &LateContext, id: NodeId) -> bool {
104 let parent_id = cx.tcx.hir.get_parent(id);
105 match MirSource::from_node(cx.tcx, parent_id) {
106 MirSource::Fn(_) => false,
107 MirSource::Const(_) |
108 MirSource::Static(..) |
109 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 {// don't treat range expressions desugared to structs as "in_macro"
117 ExpnFormat::CompilerDesugaring(name) => name != "...",
123 /// Returns true if the macro that expanded the crate was outside of the
124 /// current crate or was a
126 pub fn in_external_macro<'a, T: LintContext<'a>>(cx: &T, span: Span) -> bool {
127 /// Invokes `in_macro` with the expansion info of the given span slightly
128 /// heavy, try to use
129 /// this after other checks have already happened.
130 fn in_macro_ext<'a, T: LintContext<'a>>(cx: &T, info: &ExpnInfo) -> bool {
131 // no ExpnInfo = no macro
132 if let ExpnFormat::MacroAttribute(..) = info.callee.format {
133 // these are all plugins
136 // no span for the callee = external macro
137 info.callee.span.map_or(true, |span| {
138 // no snippet = external macro or compiler-builtin expansion
139 cx.sess().codemap().span_to_snippet(span).ok().map_or(
142 !code.starts_with("macro_rules")
148 span.ctxt.outer().expn_info().map_or(false, |info| {
149 in_macro_ext(cx, &info)
153 /// Check if a `DefId`'s path matches the given absolute type path usage.
157 /// match_def_path(cx.tcx, id, &["core", "option", "Option"])
160 /// See also the `paths` module.
161 pub fn match_def_path(tcx: TyCtxt, def_id: DefId, path: &[&str]) -> bool {
164 struct AbsolutePathBuffer {
165 names: Vec<symbol::InternedString>,
168 impl ty::item_path::ItemPathBuffer for AbsolutePathBuffer {
169 fn root_mode(&self) -> &ty::item_path::RootMode {
170 const ABSOLUTE: &'static ty::item_path::RootMode = &ty::item_path::RootMode::Absolute;
174 fn push(&mut self, text: &str) {
175 self.names.push(symbol::Symbol::intern(text).as_str());
179 let mut apb = AbsolutePathBuffer { names: vec![] };
181 tcx.push_item_path(&mut apb, def_id);
183 apb.names.len() == path.len() &&
184 apb.names.into_iter().zip(path.iter()).all(
189 /// Check if type is struct, enum or union type with given def path.
190 pub fn match_type(cx: &LateContext, ty: Ty, path: &[&str]) -> bool {
192 ty::TyAdt(adt, _) => match_def_path(cx.tcx, adt.did, path),
197 /// Check if the method call given in `expr` belongs to given type.
198 pub fn match_impl_method(cx: &LateContext, expr: &Expr, path: &[&str]) -> bool {
199 let method_call = cx.tables.type_dependent_defs[&expr.id];
200 let trt_id = cx.tcx.impl_of_method(method_call.def_id());
201 if let Some(trt_id) = trt_id {
202 match_def_path(cx.tcx, trt_id, path)
208 /// Check if the method call given in `expr` belongs to given trait.
209 pub fn match_trait_method(cx: &LateContext, expr: &Expr, path: &[&str]) -> bool {
210 let method_call = cx.tables.type_dependent_defs[&expr.id];
211 let trt_id = cx.tcx.trait_of_item(method_call.def_id());
212 if let Some(trt_id) = trt_id {
213 match_def_path(cx.tcx, trt_id, path)
219 pub fn last_path_segment(path: &QPath) -> &PathSegment {
221 QPath::Resolved(_, ref path) => {
222 path.segments.last().expect(
223 "A path must have at least one segment",
226 QPath::TypeRelative(_, ref seg) => seg,
230 pub fn single_segment_path(path: &QPath) -> Option<&PathSegment> {
232 QPath::Resolved(_, ref path) if path.segments.len() == 1 => Some(&path.segments[0]),
233 QPath::Resolved(..) => None,
234 QPath::TypeRelative(_, ref seg) => Some(seg),
238 /// Match a `Path` against a slice of segment string literals.
242 /// match_path(path, &["std", "rt", "begin_unwind"])
244 pub fn match_path(path: &QPath, segments: &[&str]) -> bool {
246 QPath::Resolved(_, ref path) => match_path_old(path, segments),
247 QPath::TypeRelative(ref ty, ref segment) => {
249 TyPath(ref inner_path) => {
250 !segments.is_empty() && match_path(inner_path, &segments[..(segments.len() - 1)]) &&
251 segment.name == segments[segments.len() - 1]
259 pub fn match_path_old(path: &Path, segments: &[&str]) -> bool {
260 path.segments.iter().rev().zip(segments.iter().rev()).all(
261 |(a, b)| a.name == *b,
265 /// Match a `Path` against a slice of segment string literals, e.g.
269 /// match_path(path, &["std", "rt", "begin_unwind"])
271 pub fn match_path_ast(path: &ast::Path, segments: &[&str]) -> bool {
272 path.segments.iter().rev().zip(segments.iter().rev()).all(
273 |(a, b)| a.identifier.name == *b,
277 /// Get the definition associated to a path.
278 pub fn path_to_def(cx: &LateContext, path: &[&str]) -> Option<def::Def> {
279 let cstore = &cx.tcx.sess.cstore;
281 let crates = cstore.crates();
282 let krate = crates.iter().find(
283 |&&krate| cstore.crate_name(krate) == path[0],
285 if let Some(krate) = krate {
288 index: CRATE_DEF_INDEX,
290 let mut items = cstore.item_children(krate, cx.tcx.sess);
291 let mut path_it = path.iter().skip(1).peekable();
294 let segment = match path_it.next() {
295 Some(segment) => segment,
299 for item in &mem::replace(&mut items, vec![]) {
300 if item.ident.name == *segment {
301 if path_it.peek().is_none() {
302 return Some(item.def);
305 items = cstore.item_children(item.def.def_id(), cx.tcx.sess);
315 /// Convenience function to get the `DefId` of a trait by path.
316 pub fn get_trait_def_id(cx: &LateContext, path: &[&str]) -> Option<DefId> {
317 let def = match path_to_def(cx, path) {
323 def::Def::Trait(trait_id) => Some(trait_id),
328 /// Check whether a type implements a trait.
329 /// See also `get_trait_def_id`.
330 pub fn implements_trait<'a, 'tcx>(
331 cx: &LateContext<'a, 'tcx>,
334 ty_params: &[Ty<'tcx>],
336 let ty = cx.tcx.erase_regions(&ty);
337 let obligation = cx.tcx.predicate_for_trait_def(
339 traits::ObligationCause::dummy(),
345 cx.tcx.infer_ctxt().enter(|infcx| {
346 traits::SelectionContext::new(&infcx).evaluate_obligation_conservatively(&obligation)
350 /// Resolve the definition of a node from its `NodeId`.
351 pub fn resolve_node(cx: &LateContext, qpath: &QPath, id: NodeId) -> def::Def {
352 cx.tables.qpath_def(qpath, id)
355 /// Match an `Expr` against a chain of methods, and return the matched `Expr`s.
357 /// For example, if `expr` represents the `.baz()` in `foo.bar().baz()`,
358 /// `matched_method_chain(expr, &["bar", "baz"])` will return a `Vec`
359 /// containing the `Expr`s for
360 /// `.bar()` and `.baz()`
361 pub fn method_chain_args<'a>(expr: &'a Expr, methods: &[&str]) -> Option<Vec<&'a [Expr]>> {
362 let mut current = expr;
363 let mut matched = Vec::with_capacity(methods.len());
364 for method_name in methods.iter().rev() {
365 // method chains are stored last -> first
366 if let ExprMethodCall(ref path, _, ref args) = current.node {
367 if path.name == *method_name {
368 if args.iter().any(|e| in_macro(e.span)) {
371 matched.push(&**args); // build up `matched` backwards
372 current = &args[0] // go to parent expression
380 matched.reverse(); // reverse `matched`, so that it is in the same order as `methods`
385 /// Get the name of the item the expression is in, if available.
386 pub fn get_item_name(cx: &LateContext, expr: &Expr) -> Option<Name> {
387 let parent_id = cx.tcx.hir.get_parent(expr.id);
388 match cx.tcx.hir.find(parent_id) {
389 Some(Node::NodeItem(&Item { ref name, .. })) |
390 Some(Node::NodeTraitItem(&TraitItem { ref name, .. })) |
391 Some(Node::NodeImplItem(&ImplItem { ref name, .. })) => Some(*name),
396 /// Convert a span to a code snippet if available, otherwise use default.
400 /// snippet(cx, expr.span, "..")
402 pub fn snippet<'a, 'b, T: LintContext<'b>>(cx: &T, span: Span, default: &'a str) -> Cow<'a, str> {
403 snippet_opt(cx, span).map_or_else(|| Cow::Borrowed(default), From::from)
406 /// Convert a span to a code snippet. Returns `None` if not available.
407 pub fn snippet_opt<'a, T: LintContext<'a>>(cx: &T, span: Span) -> Option<String> {
408 cx.sess().codemap().span_to_snippet(span).ok()
411 /// Convert a span (from a block) to a code snippet if available, otherwise use
413 /// This trims the code of indentation, except for the first line. Use it for
414 /// blocks or block-like
415 /// things which need to be printed as such.
419 /// snippet(cx, expr.span, "..")
421 pub fn snippet_block<'a, 'b, T: LintContext<'b>>(cx: &T, span: Span, default: &'a str) -> Cow<'a, str> {
422 let snip = snippet(cx, span, default);
423 trim_multiline(snip, true)
426 /// Like `snippet_block`, but add braces if the expr is not an `ExprBlock`.
427 /// Also takes an `Option<String>` which can be put inside the braces.
428 pub fn expr_block<'a, 'b, T: LintContext<'b>>(
431 option: Option<String>,
434 let code = snippet_block(cx, expr.span, default);
435 let string = option.unwrap_or_default();
436 if let ExprBlock(_) = expr.node {
437 Cow::Owned(format!("{}{}", code, string))
438 } else if string.is_empty() {
439 Cow::Owned(format!("{{ {} }}", code))
441 Cow::Owned(format!("{{\n{};\n{}\n}}", code, string))
445 /// Trim indentation from a multiline string with possibility of ignoring the
447 pub fn trim_multiline(s: Cow<str>, ignore_first: bool) -> Cow<str> {
448 let s_space = trim_multiline_inner(s, ignore_first, ' ');
449 let s_tab = trim_multiline_inner(s_space, ignore_first, '\t');
450 trim_multiline_inner(s_tab, ignore_first, ' ')
453 fn trim_multiline_inner(s: Cow<str>, ignore_first: bool, ch: char) -> Cow<str> {
455 .skip(ignore_first as usize)
460 // ignore empty lines
463 .find(|&(_, x)| x != ch)
464 .unwrap_or((l.len(), ch))
475 .map(|(i, l)| if (ignore_first && i == 0) || l.is_empty() {
488 /// Get a parent expressions if any – this is useful to constrain a lint.
489 pub fn get_parent_expr<'c>(cx: &'c LateContext, e: &Expr) -> Option<&'c Expr> {
490 let map = &cx.tcx.hir;
491 let node_id: NodeId = e.id;
492 let parent_id: NodeId = map.get_parent_node(node_id);
493 if node_id == parent_id {
496 map.find(parent_id).and_then(
497 |node| if let Node::NodeExpr(parent) =
507 pub fn get_enclosing_block<'a, 'tcx: 'a>(cx: &LateContext<'a, 'tcx>, node: NodeId) -> Option<&'tcx Block> {
508 let map = &cx.tcx.hir;
509 let enclosing_node = map.get_enclosing_scope(node).and_then(|enclosing_id| {
510 map.find(enclosing_id)
512 if let Some(node) = enclosing_node {
514 Node::NodeBlock(block) => Some(block),
515 Node::NodeItem(&Item { node: ItemFn(_, _, _, _, _, eid), .. }) => {
516 match cx.tcx.hir.body(eid).value.node {
517 ExprBlock(ref block) => Some(block),
528 pub struct DiagnosticWrapper<'a>(pub DiagnosticBuilder<'a>);
530 impl<'a> Drop for DiagnosticWrapper<'a> {
536 impl<'a> DiagnosticWrapper<'a> {
537 fn wiki_link(&mut self, lint: &'static Lint) {
538 if env::var("CLIPPY_DISABLE_WIKI_LINKS").is_err() {
539 self.0.help(&format!(
540 "for further information visit https://github.com/Manishearth/rust-clippy/wiki#{}",
547 pub fn span_lint<'a, T: LintContext<'a>>(cx: &T, lint: &'static Lint, sp: Span, msg: &str) {
548 DiagnosticWrapper(cx.struct_span_lint(lint, sp, msg)).wiki_link(lint);
551 pub fn span_help_and_lint<'a, 'tcx: 'a, T: LintContext<'tcx>>(
558 let mut db = DiagnosticWrapper(cx.struct_span_lint(lint, span, msg));
563 pub fn span_note_and_lint<'a, 'tcx: 'a, T: LintContext<'tcx>>(
571 let mut db = DiagnosticWrapper(cx.struct_span_lint(lint, span, msg));
572 if note_span == span {
575 db.0.span_note(note_span, note);
580 pub fn span_lint_and_then<'a, 'tcx: 'a, T: LintContext<'tcx>, F>(
587 F: for<'b> FnOnce(&mut DiagnosticBuilder<'b>),
589 let mut db = DiagnosticWrapper(cx.struct_span_lint(lint, sp, msg));
594 pub fn span_lint_and_sugg<'a, 'tcx: 'a, T: LintContext<'tcx>>(
602 span_lint_and_then(cx, lint, sp, msg, |db| { db.span_suggestion(sp, help, sugg); });
605 /// Create a suggestion made from several `span → replacement`.
607 /// Note: in the JSON format (used by `compiletest_rs`), the help message will
609 /// replacement. In human-readable format though, it only appears once before
610 /// the whole suggestion.
611 pub fn multispan_sugg(db: &mut DiagnosticBuilder, help_msg: String, sugg: Vec<(Span, String)>) {
612 let sugg = rustc_errors::CodeSuggestion {
613 substitution_parts: sugg.into_iter()
615 rustc_errors::Substitution {
617 substitutions: vec![sub],
622 show_code_when_inline: true,
624 db.suggestions.push(sugg);
627 /// Return the base type for references and raw pointers.
628 pub fn walk_ptrs_ty(ty: Ty) -> Ty {
630 ty::TyRef(_, ref tm) => walk_ptrs_ty(tm.ty),
635 /// Return the base type for references and raw pointers, and count reference
637 pub fn walk_ptrs_ty_depth(ty: Ty) -> (Ty, usize) {
638 fn inner(ty: Ty, depth: usize) -> (Ty, usize) {
640 ty::TyRef(_, ref tm) => inner(tm.ty, depth + 1),
647 /// Check whether the given expression is a constant literal of the given value.
648 pub fn is_integer_literal(expr: &Expr, value: u128) -> bool {
649 // FIXME: use constant folding
650 if let ExprLit(ref spanned) = expr.node {
651 if let LitKind::Int(v, _) = spanned.node {
658 pub fn is_adjusted(cx: &LateContext, e: &Expr) -> bool {
659 cx.tables.adjustments.get(&e.id).is_some()
662 pub struct LimitStack {
666 impl Drop for LimitStack {
668 assert_eq!(self.stack.len(), 1);
673 pub fn new(limit: u64) -> LimitStack {
674 LimitStack { stack: vec![limit] }
676 pub fn limit(&self) -> u64 {
677 *self.stack.last().expect(
678 "there should always be a value in the stack",
681 pub fn push_attrs(&mut self, sess: &Session, attrs: &[ast::Attribute], name: &'static str) {
682 let stack = &mut self.stack;
683 parse_attrs(sess, attrs, name, |val| stack.push(val));
685 pub fn pop_attrs(&mut self, sess: &Session, attrs: &[ast::Attribute], name: &'static str) {
686 let stack = &mut self.stack;
687 parse_attrs(sess, attrs, name, |val| assert_eq!(stack.pop(), Some(val)));
691 fn parse_attrs<F: FnMut(u64)>(sess: &Session, attrs: &[ast::Attribute], name: &'static str, mut f: F) {
693 if attr.is_sugared_doc {
696 if let Some(ref value) = attr.value_str() {
697 if attr.name().map_or(false, |n| n == name) {
698 if let Ok(value) = FromStr::from_str(&value.as_str()) {
699 attr::mark_used(attr);
702 sess.span_err(attr.span, "not a number");
709 /// Return the pre-expansion span if is this comes from an expansion of the
711 /// See also `is_direct_expn_of`.
712 pub fn is_expn_of(mut span: Span, name: &str) -> Option<Span> {
714 let span_name_span = span.ctxt.outer().expn_info().map(|ei| {
715 (ei.callee.name(), ei.call_site)
718 match span_name_span {
719 Some((mac_name, new_span)) if mac_name == name => return Some(new_span),
721 Some((_, new_span)) => span = new_span,
726 /// Return the pre-expansion span if is this directly comes from an expansion
727 /// of the macro `name`.
728 /// The difference with `is_expn_of` is that in
732 /// `42` is considered expanded from `foo!` and `bar!` by `is_expn_of` but only
734 /// `is_direct_expn_of`.
735 pub fn is_direct_expn_of(span: Span, name: &str) -> Option<Span> {
736 let span_name_span = span.ctxt.outer().expn_info().map(|ei| {
737 (ei.callee.name(), ei.call_site)
740 match span_name_span {
741 Some((mac_name, new_span)) if mac_name == name => Some(new_span),
746 /// Return the index of the character after the first camel-case component of
748 pub fn camel_case_until(s: &str) -> usize {
749 let mut iter = s.char_indices();
750 if let Some((_, first)) = iter.next() {
751 if !first.is_uppercase() {
761 if c.is_lowercase() {
766 } else if c.is_uppercase() {
769 } else if !c.is_lowercase() {
773 if up { last_i } else { s.len() }
776 /// Return index of the last camel-case component of `s`.
777 pub fn camel_case_from(s: &str) -> usize {
778 let mut iter = s.char_indices().rev();
779 if let Some((_, first)) = iter.next() {
780 if !first.is_lowercase() {
787 let mut last_i = s.len();
790 if c.is_uppercase() {
793 } else if !c.is_lowercase() {
796 } else if c.is_lowercase() {
805 /// Convenience function to get the return type of a function
806 pub fn return_ty<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, fn_item: NodeId) -> Ty<'tcx> {
807 let fn_def_id = cx.tcx.hir.local_def_id(fn_item);
808 let ret_ty = cx.tcx.fn_sig(fn_def_id).output();
809 cx.tcx.erase_late_bound_regions(&ret_ty)
812 /// Check if two types are the same.
813 // FIXME: this works correctly for lifetimes bounds (`for <'a> Foo<'a>` == `for
815 // not for type parameters.
816 pub fn same_tys<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, a: Ty<'tcx>, b: Ty<'tcx>) -> bool {
817 cx.tcx.infer_ctxt().enter(|infcx| {
818 infcx.can_eq(cx.param_env, a, b).is_ok()
822 /// Return whether the given type is an `unsafe` function.
823 pub fn type_is_unsafe_function<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, ty: Ty<'tcx>) -> bool {
825 ty::TyFnDef(..) | ty::TyFnPtr(_) => ty.fn_sig(cx.tcx).unsafety() == Unsafety::Unsafe,
830 pub fn is_copy<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, ty: Ty<'tcx>) -> bool {
831 !ty.moves_by_default(cx.tcx.global_tcx(), cx.param_env, DUMMY_SP)
834 /// Return whether a pattern is refutable.
835 pub fn is_refutable(cx: &LateContext, pat: &Pat) -> bool {
836 fn is_enum_variant(cx: &LateContext, qpath: &QPath, did: NodeId) -> bool {
838 cx.tables.qpath_def(qpath, did),
839 def::Def::Variant(..) | def::Def::VariantCtor(..)
843 fn are_refutable<'a, I: Iterator<Item = &'a Pat>>(cx: &LateContext, mut i: I) -> bool {
844 i.any(|pat| is_refutable(cx, pat))
848 PatKind::Binding(..) |
849 PatKind::Wild => false,
850 PatKind::Box(ref pat) |
851 PatKind::Ref(ref pat, _) => is_refutable(cx, pat),
853 PatKind::Range(..) => true,
854 PatKind::Path(ref qpath) => is_enum_variant(cx, qpath, pat.id),
855 PatKind::Tuple(ref pats, _) => are_refutable(cx, pats.iter().map(|pat| &**pat)),
856 PatKind::Struct(ref qpath, ref fields, _) => {
857 if is_enum_variant(cx, qpath, pat.id) {
860 are_refutable(cx, fields.iter().map(|field| &*field.node.pat))
863 PatKind::TupleStruct(ref qpath, ref pats, _) => {
864 if is_enum_variant(cx, qpath, pat.id) {
867 are_refutable(cx, pats.iter().map(|pat| &**pat))
870 PatKind::Slice(ref head, ref middle, ref tail) => {
873 head.iter().chain(middle).chain(tail.iter()).map(
881 /// Checks for the `#[automatically_derived]` attribute all `#[derive]`d
882 /// implementations have.
883 pub fn is_automatically_derived(attrs: &[ast::Attribute]) -> bool {
884 attr::contains_name(attrs, "automatically_derived")
887 /// Remove blocks around an expression.
889 /// Ie. `x`, `{ x }` and `{{{{ x }}}}` all give `x`. `{ x; y }` and `{}` return
891 pub fn remove_blocks(expr: &Expr) -> &Expr {
892 if let ExprBlock(ref block) = expr.node {
893 if block.stmts.is_empty() {
894 if let Some(ref expr) = block.expr {
907 pub fn opt_def_id(def: Def) -> Option<DefId> {
913 Def::VariantCtor(id, ..) |
916 Def::AssociatedTy(id) |
919 Def::StructCtor(id, ..) |
924 Def::AssociatedConst(id) |
928 Def::GlobalAsm(id) => Some(id),
930 Def::Label(..) | Def::PrimTy(..) | Def::SelfTy(..) | Def::Err => None,
934 pub fn is_self(slf: &Arg) -> bool {
935 if let PatKind::Binding(_, _, name, _) = slf.pat.node {
936 name.node == keywords::SelfValue.name()
942 pub fn is_self_ty(slf: &hir::Ty) -> bool {
944 let TyPath(ref qp) = slf.node,
945 let QPath::Resolved(None, ref path) = *qp,
946 let Def::SelfTy(..) = path.def,
953 pub fn iter_input_pats<'tcx>(decl: &FnDecl, body: &'tcx Body) -> impl Iterator<Item = &'tcx Arg> {
954 (0..decl.inputs.len()).map(move |i| &body.arguments[i])
957 /// Check if a given expression is a match expression
958 /// expanded from `?` operator or `try` macro.
959 pub fn is_try(expr: &Expr) -> Option<&Expr> {
960 fn is_ok(arm: &Arm) -> bool {
962 let PatKind::TupleStruct(ref path, ref pat, None) = arm.pats[0].node,
963 match_path(path, &paths::RESULT_OK[1..]),
964 let PatKind::Binding(_, defid, _, None) = pat[0].node,
965 let ExprPath(QPath::Resolved(None, ref path)) = arm.body.node,
966 path.def.def_id() == defid,
973 fn is_err(arm: &Arm) -> bool {
974 if let PatKind::TupleStruct(ref path, _, _) = arm.pats[0].node {
975 match_path(path, &paths::RESULT_ERR[1..])
981 if let ExprMatch(_, ref arms, ref source) = expr.node {
982 // desugared from a `?` operator
983 if let MatchSource::TryDesugar = *source {
989 arms[0].pats.len() == 1 && arms[0].guard.is_none(),
990 arms[1].pats.len() == 1 && arms[1].guard.is_none(),
991 (is_ok(&arms[0]) && is_err(&arms[1])) ||
992 (is_ok(&arms[1]) && is_err(&arms[0])),
1001 pub fn type_size<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, ty: Ty<'tcx>) -> Option<u64> {
1002 ty.layout(cx.tcx, cx.param_env).ok().map(|layout| {
1003 layout.size(cx.tcx).bytes()
1007 /// Returns true if the lint is allowed in the current context
1009 /// Useful for skipping long running code when it's unnecessary
1010 pub fn is_allowed(cx: &LateContext, lint: &'static Lint, id: NodeId) -> bool {
1011 cx.tcx.lint_level_at_node(lint, id).0 == Level::Allow