3 use rustc::hir::def_id::{DefId, CRATE_DEF_INDEX};
4 use rustc::hir::def::Def;
5 use rustc::hir::map::Node;
6 use rustc::lint::{LintContext, LateContext, Level, Lint};
7 use rustc::session::Session;
8 use rustc::traits::Reveal;
10 use rustc::ty::subst::Subst;
16 use std::str::FromStr;
17 use syntax::ast::{self, LitKind};
19 use syntax::codemap::{ExpnFormat, ExpnInfo, MultiSpan, Span, DUMMY_SP};
20 use syntax::errors::DiagnosticBuilder;
22 use syntax::symbol::keywords;
31 pub mod internal_lints;
32 pub use self::hir::{SpanlessEq, SpanlessHash};
34 pub type MethodArgs = HirVec<P<Expr>>;
36 /// Produce a nested chain of if-lets and ifs from the patterns:
51 /// if let Some(y) = x {
53 /// if let Some(z) = y {
60 macro_rules! if_let_chain {
61 ([let $pat:pat = $expr:expr, $($tt:tt)+], $block:block) => {
63 if_let_chain!{ [$($tt)+], $block }
66 ([let $pat:pat = $expr:expr], $block:block) => {
71 ([let $pat:pat = $expr:expr,], $block:block) => {
76 ([$expr:expr, $($tt:tt)+], $block:block) => {
78 if_let_chain!{ [$($tt)+], $block }
81 ([$expr:expr], $block:block) => {
86 ([$expr:expr,], $block:block) => {
95 /// Returns true if the two spans come from differing expansions (i.e. one is from a macro and one
97 pub fn differing_macro_contexts(lhs: Span, rhs: Span) -> bool {
98 rhs.expn_id != lhs.expn_id
100 /// Returns true if this `expn_info` was expanded by any macro.
101 pub fn in_macro<'a, T: LintContext<'a>>(cx: &T, span: Span) -> bool {
102 cx.sess().codemap().with_expn_info(span.expn_id, |info| {
105 match info.callee.format {
106 // don't treat range expressions desugared to structs as "in_macro"
107 ExpnFormat::CompilerDesugaring(name) => name != "...",
116 /// Returns true if the macro that expanded the crate was outside of the current crate or was a
118 pub fn in_external_macro<'a, T: LintContext<'a>>(cx: &T, span: Span) -> bool {
119 /// Invokes `in_macro` with the expansion info of the given span slightly heavy, try to use
120 /// this after other checks have already happened.
121 fn in_macro_ext<'a, T: LintContext<'a>>(cx: &T, opt_info: Option<&ExpnInfo>) -> bool {
122 // no ExpnInfo = no macro
123 opt_info.map_or(false, |info| {
124 if let ExpnFormat::MacroAttribute(..) = info.callee.format {
125 // these are all plugins
128 // no span for the callee = external macro
129 info.callee.span.map_or(true, |span| {
130 // no snippet = external macro or compiler-builtin expansion
131 cx.sess().codemap().span_to_snippet(span).ok().map_or(true, |code| !code.starts_with("macro_rules"))
136 cx.sess().codemap().with_expn_info(span.expn_id, |info| in_macro_ext(cx, info))
139 /// Check if a `DefId`'s path matches the given absolute type path usage.
143 /// match_def_path(cx.tcx, id, &["core", "option", "Option"])
146 /// See also the `paths` module.
147 pub fn match_def_path(tcx: ty::TyCtxt, def_id: DefId, path: &[&str]) -> bool {
150 struct AbsolutePathBuffer {
151 names: Vec<symbol::InternedString>,
154 impl ty::item_path::ItemPathBuffer for AbsolutePathBuffer {
155 fn root_mode(&self) -> &ty::item_path::RootMode {
156 const ABSOLUTE: &'static ty::item_path::RootMode = &ty::item_path::RootMode::Absolute;
160 fn push(&mut self, text: &str) {
161 self.names.push(symbol::Symbol::intern(text).as_str());
165 let mut apb = AbsolutePathBuffer { names: vec![] };
167 tcx.push_item_path(&mut apb, def_id);
169 apb.names.len() == path.len() && apb.names.iter().zip(path.iter()).all(|(a, &b)| &**a == b)
172 /// Check if type is struct, enum or union type with given def path.
173 pub fn match_type(cx: &LateContext, ty: ty::Ty, path: &[&str]) -> bool {
175 ty::TyAdt(adt, _) => match_def_path(cx.tcx, adt.did, path),
180 /// Check if the method call given in `expr` belongs to given type.
181 pub fn match_impl_method(cx: &LateContext, expr: &Expr, path: &[&str]) -> bool {
182 let method_call = ty::MethodCall::expr(expr.id);
184 let trt_id = cx.tables
187 .and_then(|callee| cx.tcx.impl_of_method(callee.def_id));
188 if let Some(trt_id) = trt_id {
189 match_def_path(cx.tcx, trt_id, path)
195 /// Check if the method call given in `expr` belongs to given trait.
196 pub fn match_trait_method(cx: &LateContext, expr: &Expr, path: &[&str]) -> bool {
197 let method_call = ty::MethodCall::expr(expr.id);
199 let trt_id = cx.tables
202 .and_then(|callee| cx.tcx.trait_of_item(callee.def_id));
203 if let Some(trt_id) = trt_id {
204 match_def_path(cx.tcx, trt_id, path)
210 pub fn last_path_segment(path: &QPath) -> &PathSegment {
212 QPath::Resolved(_, ref path) => {
215 .expect("A path must have at least one segment")
217 QPath::TypeRelative(_, ref seg) => seg,
221 pub fn single_segment_path(path: &QPath) -> Option<&PathSegment> {
223 QPath::Resolved(_, ref path) if path.segments.len() == 1 => Some(&path.segments[0]),
224 QPath::Resolved(..) => None,
225 QPath::TypeRelative(_, ref seg) => Some(seg),
229 /// Match a `Path` against a slice of segment string literals.
233 /// match_path(path, &["std", "rt", "begin_unwind"])
235 pub fn match_path(path: &QPath, segments: &[&str]) -> bool {
237 QPath::Resolved(_, ref path) => match_path_old(path, segments),
238 QPath::TypeRelative(ref ty, ref segment) => {
240 TyPath(ref inner_path) => {
241 !segments.is_empty() && match_path(inner_path, &segments[..(segments.len() - 1)]) &&
242 segment.name == segments[segments.len() - 1]
250 pub fn match_path_old(path: &Path, segments: &[&str]) -> bool {
251 path.segments.iter().rev().zip(segments.iter().rev()).all(|(a, b)| a.name == *b)
254 /// Match a `Path` against a slice of segment string literals, e.g.
258 /// match_path(path, &["std", "rt", "begin_unwind"])
260 pub fn match_path_ast(path: &ast::Path, segments: &[&str]) -> bool {
261 path.segments.iter().rev().zip(segments.iter().rev()).all(|(a, b)| a.identifier.name == *b)
264 /// Get the definition associated to a path.
265 /// TODO: investigate if there is something more efficient for that.
266 pub fn path_to_def(cx: &LateContext, path: &[&str]) -> Option<def::Def> {
267 let cstore = &cx.tcx.sess.cstore;
269 let crates = cstore.crates();
270 let krate = crates.iter().find(|&&krate| cstore.crate_name(krate) == path[0]);
271 if let Some(krate) = krate {
274 index: CRATE_DEF_INDEX,
276 let mut items = cstore.item_children(krate);
277 let mut path_it = path.iter().skip(1).peekable();
280 let segment = match path_it.next() {
281 Some(segment) => segment,
285 for item in &mem::replace(&mut items, vec![]) {
286 if item.name == *segment {
287 if path_it.peek().is_none() {
288 return Some(item.def);
291 items = cstore.item_children(item.def.def_id());
301 /// Convenience function to get the `DefId` of a trait by path.
302 pub fn get_trait_def_id(cx: &LateContext, path: &[&str]) -> Option<DefId> {
303 let def = match path_to_def(cx, path) {
309 def::Def::Trait(trait_id) => Some(trait_id),
314 /// Check whether a type implements a trait.
315 /// See also `get_trait_def_id`.
316 pub fn implements_trait<'a, 'tcx>(
317 cx: &LateContext<'a, 'tcx>,
320 ty_params: &[ty::Ty<'tcx>],
321 parent_node_id: Option<NodeId>
323 cx.tcx.populate_implementations_for_trait_if_necessary(trait_id);
325 let ty = cx.tcx.erase_regions(&ty);
326 let mut b = if let Some(id) = parent_node_id {
327 cx.tcx.infer_ctxt(BodyId { node_id: id }, Reveal::All)
329 cx.tcx.infer_ctxt((), Reveal::All)
332 let obligation = cx.tcx.predicate_for_trait_def(traits::ObligationCause::dummy(), trait_id, 0, ty, ty_params);
334 traits::SelectionContext::new(&infcx).evaluate_obligation_conservatively(&obligation)
338 /// Resolve the definition of a node from its `NodeId`.
339 pub fn resolve_node(cx: &LateContext, qpath: &QPath, id: NodeId) -> def::Def {
340 cx.tables.qpath_def(qpath, id)
343 /// Match an `Expr` against a chain of methods, and return the matched `Expr`s.
345 /// For example, if `expr` represents the `.baz()` in `foo.bar().baz()`,
346 /// `matched_method_chain(expr, &["bar", "baz"])` will return a `Vec` containing the `Expr`s for
347 /// `.bar()` and `.baz()`
348 pub fn method_chain_args<'a>(expr: &'a Expr, methods: &[&str]) -> Option<Vec<&'a [Expr]>> {
349 let mut current = expr;
350 let mut matched = Vec::with_capacity(methods.len());
351 for method_name in methods.iter().rev() {
352 // method chains are stored last -> first
353 if let ExprMethodCall(ref name, _, ref args) = current.node {
354 if name.node == *method_name {
355 matched.push(&**args); // build up `matched` backwards
356 current = &args[0] // go to parent expression
364 matched.reverse(); // reverse `matched`, so that it is in the same order as `methods`
369 /// Get the name of the item the expression is in, if available.
370 pub fn get_item_name(cx: &LateContext, expr: &Expr) -> Option<Name> {
371 let parent_id = cx.tcx.hir.get_parent(expr.id);
372 match cx.tcx.hir.find(parent_id) {
373 Some(Node::NodeItem(&Item { ref name, .. })) |
374 Some(Node::NodeTraitItem(&TraitItem { ref name, .. })) |
375 Some(Node::NodeImplItem(&ImplItem { ref name, .. })) => Some(*name),
380 /// Convert a span to a code snippet if available, otherwise use default.
384 /// snippet(cx, expr.span, "..")
386 pub fn snippet<'a, 'b, T: LintContext<'b>>(cx: &T, span: Span, default: &'a str) -> Cow<'a, str> {
387 cx.sess().codemap().span_to_snippet(span).map(From::from).unwrap_or_else(|_| Cow::Borrowed(default))
390 /// Convert a span to a code snippet. Returns `None` if not available.
391 pub fn snippet_opt<'a, T: LintContext<'a>>(cx: &T, span: Span) -> Option<String> {
392 cx.sess().codemap().span_to_snippet(span).ok()
395 /// Convert a span (from a block) to a code snippet if available, otherwise use default.
396 /// This trims the code of indentation, except for the first line. Use it for blocks or block-like
397 /// things which need to be printed as such.
401 /// snippet(cx, expr.span, "..")
403 pub fn snippet_block<'a, 'b, T: LintContext<'b>>(cx: &T, span: Span, default: &'a str) -> Cow<'a, str> {
404 let snip = snippet(cx, span, default);
405 trim_multiline(snip, true)
408 /// Like `snippet_block`, but add braces if the expr is not an `ExprBlock`.
409 /// Also takes an `Option<String>` which can be put inside the braces.
410 pub fn expr_block<'a, 'b, T: LintContext<'b>>(
413 option: Option<String>,
416 let code = snippet_block(cx, expr.span, default);
417 let string = option.unwrap_or_default();
418 if let ExprBlock(_) = expr.node {
419 Cow::Owned(format!("{}{}", code, string))
420 } else if string.is_empty() {
421 Cow::Owned(format!("{{ {} }}", code))
423 Cow::Owned(format!("{{\n{};\n{}\n}}", code, string))
427 /// Trim indentation from a multiline string with possibility of ignoring the first line.
428 pub fn trim_multiline(s: Cow<str>, ignore_first: bool) -> Cow<str> {
429 let s_space = trim_multiline_inner(s, ignore_first, ' ');
430 let s_tab = trim_multiline_inner(s_space, ignore_first, '\t');
431 trim_multiline_inner(s_tab, ignore_first, ' ')
434 fn trim_multiline_inner(s: Cow<str>, ignore_first: bool, ch: char) -> Cow<str> {
436 .skip(ignore_first as usize)
441 // ignore empty lines
442 Some(l.char_indices()
443 .find(|&(_, x)| x != ch)
444 .unwrap_or((l.len(), ch))
453 .map(|(i, l)| if (ignore_first && i == 0) || l.is_empty() {
465 /// Get a parent expressions if any – this is useful to constrain a lint.
466 pub fn get_parent_expr<'c>(cx: &'c LateContext, e: &Expr) -> Option<&'c Expr> {
467 let map = &cx.tcx.hir;
468 let node_id: NodeId = e.id;
469 let parent_id: NodeId = map.get_parent_node(node_id);
470 if node_id == parent_id {
473 map.find(parent_id).and_then(|node| if let Node::NodeExpr(parent) = node {
480 pub fn get_enclosing_block<'a, 'tcx: 'a>(cx: &LateContext<'a, 'tcx>, node: NodeId) -> Option<&'tcx Block> {
481 let map = &cx.tcx.hir;
482 let enclosing_node = map.get_enclosing_scope(node)
483 .and_then(|enclosing_id| map.find(enclosing_id));
484 if let Some(node) = enclosing_node {
486 Node::NodeBlock(block) => Some(block),
487 Node::NodeItem(&Item { node: ItemFn(_, _, _, _, _, eid), .. }) => {
488 match cx.tcx.hir.body(eid).value.node {
489 ExprBlock(ref block) => Some(block),
500 pub struct DiagnosticWrapper<'a>(pub DiagnosticBuilder<'a>);
502 impl<'a> Drop for DiagnosticWrapper<'a> {
508 impl<'a> DiagnosticWrapper<'a> {
509 fn wiki_link(&mut self, lint: &'static Lint) {
510 if env::var("CLIPPY_DISABLE_WIKI_LINKS").is_err() {
511 self.0.help(&format!("for further information visit https://github.com/Manishearth/rust-clippy/wiki#{}",
517 pub fn span_lint<'a, T: LintContext<'a>>(cx: &T, lint: &'static Lint, sp: Span, msg: &str) {
518 let mut db = DiagnosticWrapper(cx.struct_span_lint(lint, sp, msg));
519 if cx.current_level(lint) != Level::Allow {
524 pub fn span_help_and_lint<'a, 'tcx: 'a, T: LintContext<'tcx>>(
531 let mut db = DiagnosticWrapper(cx.struct_span_lint(lint, span, msg));
532 if cx.current_level(lint) != Level::Allow {
538 pub fn span_note_and_lint<'a, 'tcx: 'a, T: LintContext<'tcx>>(
546 let mut db = DiagnosticWrapper(cx.struct_span_lint(lint, span, msg));
547 if cx.current_level(lint) != Level::Allow {
548 if note_span == span {
551 db.0.span_note(note_span, note);
557 pub fn span_lint_and_then<'a, 'tcx: 'a, T: LintContext<'tcx>, F>(
563 ) where F: for<'b> FnOnce(&mut DiagnosticBuilder<'b>)
565 let mut db = DiagnosticWrapper(cx.struct_span_lint(lint, sp, msg));
566 if cx.current_level(lint) != Level::Allow {
572 pub fn span_lint_and_sugg<'a, 'tcx: 'a, T: LintContext<'tcx>>(
580 span_lint_and_then(cx, lint, sp, msg, |db| { db.span_suggestion(sp, help, sugg); });
583 /// Create a suggestion made from several `span → replacement`.
585 /// Note: in the JSON format (used by `compiletest_rs`), the help message will appear once per
586 /// replacement. In human-readable format though, it only appears once before the whole suggestion.
587 pub fn multispan_sugg(db: &mut DiagnosticBuilder, help_msg: String, sugg: Vec<(Span, String)>) {
588 let sugg = rustc_errors::RenderSpan::Suggestion(rustc_errors::CodeSuggestion {
589 msp: MultiSpan::from_spans(sugg.iter().map(|&(span, _)| span).collect()),
590 substitutes: sugg.into_iter().map(|(_, subs)| subs).collect(),
593 let sub = rustc_errors::SubDiagnostic {
594 level: rustc_errors::Level::Help,
595 message: vec![(help_msg, rustc_errors::snippet::Style::LabelPrimary)],
596 span: MultiSpan::new(),
597 render_span: Some(sugg),
599 db.children.push(sub);
602 /// Return the base type for references and raw pointers.
603 pub fn walk_ptrs_ty(ty: ty::Ty) -> ty::Ty {
605 ty::TyRef(_, ref tm) => walk_ptrs_ty(tm.ty),
610 /// Return the base type for references and raw pointers, and count reference depth.
611 pub fn walk_ptrs_ty_depth(ty: ty::Ty) -> (ty::Ty, usize) {
612 fn inner(ty: ty::Ty, depth: usize) -> (ty::Ty, usize) {
614 ty::TyRef(_, ref tm) => inner(tm.ty, depth + 1),
621 /// Check whether the given expression is a constant literal of the given value.
622 pub fn is_integer_literal(expr: &Expr, value: u128) -> bool {
623 // FIXME: use constant folding
624 if let ExprLit(ref spanned) = expr.node {
625 if let LitKind::Int(v, _) = spanned.node {
632 pub fn is_adjusted(cx: &LateContext, e: &Expr) -> bool {
633 cx.tables.adjustments.get(&e.id).is_some()
636 pub struct LimitStack {
640 impl Drop for LimitStack {
642 assert_eq!(self.stack.len(), 1);
647 pub fn new(limit: u64) -> LimitStack {
648 LimitStack { stack: vec![limit] }
650 pub fn limit(&self) -> u64 {
651 *self.stack.last().expect("there should always be a value in the stack")
653 pub fn push_attrs(&mut self, sess: &Session, attrs: &[ast::Attribute], name: &'static str) {
654 let stack = &mut self.stack;
655 parse_attrs(sess, attrs, name, |val| stack.push(val));
657 pub fn pop_attrs(&mut self, sess: &Session, attrs: &[ast::Attribute], name: &'static str) {
658 let stack = &mut self.stack;
659 parse_attrs(sess, attrs, name, |val| assert_eq!(stack.pop(), Some(val)));
663 fn parse_attrs<F: FnMut(u64)>(sess: &Session, attrs: &[ast::Attribute], name: &'static str, mut f: F) {
665 if attr.is_sugared_doc {
668 if let ast::MetaItemKind::NameValue(ref value) = attr.value.node {
669 if attr.name() == name {
670 if let LitKind::Str(ref s, _) = value.node {
671 if let Ok(value) = FromStr::from_str(&*s.as_str()) {
672 attr::mark_used(attr);
675 sess.span_err(value.span, "not a number");
685 /// Return the pre-expansion span if is this comes from an expansion of the macro `name`.
686 /// See also `is_direct_expn_of`.
687 pub fn is_expn_of(cx: &LateContext, mut span: Span, name: &str) -> Option<Span> {
689 let span_name_span = cx.tcx
692 .with_expn_info(span.expn_id, |expn| expn.map(|ei| (ei.callee.name(), ei.call_site)));
694 match span_name_span {
695 Some((mac_name, new_span)) if mac_name == name => return Some(new_span),
697 Some((_, new_span)) => span = new_span,
702 /// Return the pre-expansion span if is this directly comes from an expansion of the macro `name`.
703 /// The difference with `is_expn_of` is that in
707 /// `42` is considered expanded from `foo!` and `bar!` by `is_expn_of` but only `bar!` by
708 /// `is_direct_expn_of`.
709 pub fn is_direct_expn_of(cx: &LateContext, span: Span, name: &str) -> Option<Span> {
710 let span_name_span = cx.tcx
713 .with_expn_info(span.expn_id, |expn| expn.map(|ei| (ei.callee.name(), ei.call_site)));
715 match span_name_span {
716 Some((mac_name, new_span)) if mac_name == name => Some(new_span),
721 /// Return the index of the character after the first camel-case component of `s`.
722 pub fn camel_case_until(s: &str) -> usize {
723 let mut iter = s.char_indices();
724 if let Some((_, first)) = iter.next() {
725 if !first.is_uppercase() {
735 if c.is_lowercase() {
740 } else if c.is_uppercase() {
743 } else if !c.is_lowercase() {
747 if up { last_i } else { s.len() }
750 /// Return index of the last camel-case component of `s`.
751 pub fn camel_case_from(s: &str) -> usize {
752 let mut iter = s.char_indices().rev();
753 if let Some((_, first)) = iter.next() {
754 if !first.is_lowercase() {
761 let mut last_i = s.len();
764 if c.is_uppercase() {
767 } else if !c.is_lowercase() {
770 } else if c.is_lowercase() {
779 /// Convenience function to get the return type of a function
780 pub fn return_ty<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, fn_item: NodeId) -> ty::Ty<'tcx> {
781 let parameter_env = ty::ParameterEnvironment::for_item(cx.tcx, fn_item);
782 let fn_def_id = cx.tcx.hir.local_def_id(fn_item);
783 let fn_sig = cx.tcx.item_type(fn_def_id).fn_sig();
784 let fn_sig = cx.tcx.liberate_late_bound_regions(parameter_env.free_id_outlive, fn_sig);
788 /// Check if two types are the same.
789 // FIXME: this works correctly for lifetimes bounds (`for <'a> Foo<'a>` == `for <'b> Foo<'b>` but
790 // not for type parameters.
791 pub fn same_tys<'a, 'tcx>(
792 cx: &LateContext<'a, 'tcx>,
795 parameter_item: NodeId
797 let parameter_env = ty::ParameterEnvironment::for_item(cx.tcx, parameter_item);
798 cx.tcx.infer_ctxt(parameter_env, Reveal::All).enter(|infcx| {
799 let new_a = a.subst(infcx.tcx, infcx.parameter_environment.free_substs);
800 let new_b = b.subst(infcx.tcx, infcx.parameter_environment.free_substs);
801 infcx.can_equate(&new_a, &new_b).is_ok()
805 /// Return whether the given type is an `unsafe` function.
806 pub fn type_is_unsafe_function(ty: ty::Ty) -> bool {
808 ty::TyFnDef(_, _, f) |
809 ty::TyFnPtr(f) => f.unsafety == Unsafety::Unsafe,
814 pub fn is_copy<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, ty: ty::Ty<'tcx>, env: NodeId) -> bool {
815 let env = ty::ParameterEnvironment::for_item(cx.tcx, env);
816 !ty.subst(cx.tcx, env.free_substs).moves_by_default(cx.tcx.global_tcx(), &env, DUMMY_SP)
819 /// Return whether a pattern is refutable.
820 pub fn is_refutable(cx: &LateContext, pat: &Pat) -> bool {
821 fn is_enum_variant(cx: &LateContext, qpath: &QPath, did: NodeId) -> bool {
822 matches!(cx.tables.qpath_def(qpath, did),
823 def::Def::Variant(..) | def::Def::VariantCtor(..))
826 fn are_refutable<'a, I: Iterator<Item = &'a Pat>>(cx: &LateContext, mut i: I) -> bool {
827 i.any(|pat| is_refutable(cx, pat))
831 PatKind::Binding(..) |
832 PatKind::Wild => false,
833 PatKind::Box(ref pat) |
834 PatKind::Ref(ref pat, _) => is_refutable(cx, pat),
836 PatKind::Range(..) => true,
837 PatKind::Path(ref qpath) => is_enum_variant(cx, qpath, pat.id),
838 PatKind::Tuple(ref pats, _) => are_refutable(cx, pats.iter().map(|pat| &**pat)),
839 PatKind::Struct(ref qpath, ref fields, _) => {
840 if is_enum_variant(cx, qpath, pat.id) {
843 are_refutable(cx, fields.iter().map(|field| &*field.node.pat))
846 PatKind::TupleStruct(ref qpath, ref pats, _) => {
847 if is_enum_variant(cx, qpath, pat.id) {
850 are_refutable(cx, pats.iter().map(|pat| &**pat))
853 PatKind::Slice(ref head, ref middle, ref tail) => {
854 are_refutable(cx, head.iter().chain(middle).chain(tail.iter()).map(|pat| &**pat))
859 /// Checks for the `#[automatically_derived]` attribute all `#[derive]`d implementations have.
860 pub fn is_automatically_derived(attrs: &[ast::Attribute]) -> bool {
861 attr::contains_name(attrs, "automatically_derived")
864 /// Remove blocks around an expression.
866 /// Ie. `x`, `{ x }` and `{{{{ x }}}}` all give `x`. `{ x; y }` and `{}` return themselves.
867 pub fn remove_blocks(expr: &Expr) -> &Expr {
868 if let ExprBlock(ref block) = expr.node {
869 if block.stmts.is_empty() {
870 if let Some(ref expr) = block.expr {
883 pub fn opt_def_id(def: Def) -> Option<DefId> {
889 Def::VariantCtor(id, ..) |
892 Def::AssociatedTy(id) |
895 Def::StructCtor(id, ..) |
900 Def::AssociatedConst(id) |
903 Def::Macro(id, _) => Some(id),
905 Def::Label(..) | Def::PrimTy(..) | Def::SelfTy(..) | Def::Err => None,
909 pub fn is_self(slf: &Arg) -> bool {
910 if let PatKind::Binding(_, _, name, _) = slf.pat.node {
911 name.node == keywords::SelfValue.name()
917 pub fn is_self_ty(slf: &Ty) -> bool {
919 let TyPath(ref qp) = slf.node,
920 let QPath::Resolved(None, ref path) = *qp,
921 let Def::SelfTy(..) = path.def,
928 pub fn iter_input_pats<'tcx>(decl: &FnDecl, body: &'tcx Body) -> impl Iterator<Item = &'tcx Arg> {
929 (0..decl.inputs.len()).map(move |i| &body.arguments[i])
932 /// Check if a given expression is a match expression
933 /// expanded from `?` operator or `try` macro.
934 pub fn is_try(expr: &Expr) -> Option<&Expr> {
935 fn is_ok(arm: &Arm) -> bool {
937 let PatKind::TupleStruct(ref path, ref pat, None) = arm.pats[0].node,
938 match_path(path, &paths::RESULT_OK[1..]),
939 let PatKind::Binding(_, defid, _, None) = pat[0].node,
940 let ExprPath(QPath::Resolved(None, ref path)) = arm.body.node,
941 path.def.def_id() == defid,
948 fn is_err(arm: &Arm) -> bool {
949 if let PatKind::TupleStruct(ref path, _, _) = arm.pats[0].node {
950 match_path(path, &paths::RESULT_ERR[1..])
956 if let ExprMatch(_, ref arms, ref source) = expr.node {
957 // desugared from a `?` operator
958 if let MatchSource::TryDesugar = *source {
964 arms[0].pats.len() == 1 && arms[0].guard.is_none(),
965 arms[1].pats.len() == 1 && arms[1].guard.is_none(),
966 (is_ok(&arms[0]) && is_err(&arms[1])) ||
967 (is_ok(&arms[1]) && is_err(&arms[0])),