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;
32 pub mod internal_lints;
33 pub use self::hir::{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 from a macro and one
98 pub fn differing_macro_contexts(lhs: Span, rhs: Span) -> bool {
99 rhs.expn_id != lhs.expn_id
101 /// Returns true if this `expn_info` was expanded by any macro.
102 pub fn in_macro<'a, T: LintContext<'a>>(cx: &T, span: Span) -> bool {
103 cx.sess().codemap().with_expn_info(span.expn_id, |info| {
106 match info.callee.format {
107 // don't treat range expressions desugared to structs as "in_macro"
108 ExpnFormat::CompilerDesugaring(name) => name != "...",
117 /// Returns true if the macro that expanded the crate was outside of the current crate or was a
119 pub fn in_external_macro<'a, T: LintContext<'a>>(cx: &T, span: Span) -> bool {
120 /// Invokes `in_macro` with the expansion info of the given span slightly heavy, try to use
121 /// this after other checks have already happened.
122 fn in_macro_ext<'a, T: LintContext<'a>>(cx: &T, opt_info: Option<&ExpnInfo>) -> bool {
123 // no ExpnInfo = no macro
124 opt_info.map_or(false, |info| {
125 if let ExpnFormat::MacroAttribute(..) = info.callee.format {
126 // these are all plugins
129 // no span for the callee = external macro
130 info.callee.span.map_or(true, |span| {
131 // no snippet = external macro or compiler-builtin expansion
132 cx.sess().codemap().span_to_snippet(span).ok().map_or(true, |code| !code.starts_with("macro_rules"))
137 cx.sess().codemap().with_expn_info(span.expn_id, |info| in_macro_ext(cx, info))
140 /// Check if a `DefId`'s path matches the given absolute type path usage.
144 /// match_def_path(cx.tcx, id, &["core", "option", "Option"])
147 /// See also the `paths` module.
148 pub fn match_def_path(tcx: ty::TyCtxt, def_id: DefId, path: &[&str]) -> bool {
151 struct AbsolutePathBuffer {
152 names: Vec<symbol::InternedString>,
155 impl ty::item_path::ItemPathBuffer for AbsolutePathBuffer {
156 fn root_mode(&self) -> &ty::item_path::RootMode {
157 const ABSOLUTE: &'static ty::item_path::RootMode = &ty::item_path::RootMode::Absolute;
161 fn push(&mut self, text: &str) {
162 self.names.push(symbol::Symbol::intern(text).as_str());
166 let mut apb = AbsolutePathBuffer { names: vec![] };
168 tcx.push_item_path(&mut apb, def_id);
170 apb.names.len() == path.len() && apb.names.iter().zip(path.iter()).all(|(a, &b)| &**a == b)
173 /// Check if type is struct, enum or union type with given def path.
174 pub fn match_type(cx: &LateContext, ty: ty::Ty, path: &[&str]) -> bool {
176 ty::TyAdt(adt, _) => match_def_path(cx.tcx, adt.did, path),
181 /// Check if the method call given in `expr` belongs to given type.
182 pub fn match_impl_method(cx: &LateContext, expr: &Expr, path: &[&str]) -> bool {
183 let method_call = ty::MethodCall::expr(expr.id);
185 let trt_id = cx.tables
188 .and_then(|callee| cx.tcx.impl_of_method(callee.def_id));
189 if let Some(trt_id) = trt_id {
190 match_def_path(cx.tcx, trt_id, path)
196 /// Check if the method call given in `expr` belongs to given trait.
197 pub fn match_trait_method(cx: &LateContext, expr: &Expr, path: &[&str]) -> bool {
198 let method_call = ty::MethodCall::expr(expr.id);
200 let trt_id = cx.tables
203 .and_then(|callee| cx.tcx.trait_of_item(callee.def_id));
204 if let Some(trt_id) = trt_id {
205 match_def_path(cx.tcx, trt_id, path)
211 pub fn last_path_segment(path: &QPath) -> &PathSegment {
213 QPath::Resolved(_, ref path) => {
216 .expect("A path must have at least one segment")
218 QPath::TypeRelative(_, ref seg) => seg,
222 pub fn single_segment_path(path: &QPath) -> Option<&PathSegment> {
224 QPath::Resolved(_, ref path) if path.segments.len() == 1 => Some(&path.segments[0]),
225 QPath::Resolved(..) => None,
226 QPath::TypeRelative(_, ref seg) => Some(seg),
230 /// Match a `Path` against a slice of segment string literals.
234 /// match_path(path, &["std", "rt", "begin_unwind"])
236 pub fn match_path(path: &QPath, segments: &[&str]) -> bool {
238 QPath::Resolved(_, ref path) => match_path_old(path, segments),
239 QPath::TypeRelative(ref ty, ref segment) => {
241 TyPath(ref inner_path) => {
242 segments.len() > 0 && match_path(inner_path, &segments[..(segments.len() - 1)]) &&
243 segment.name == segments[segments.len() - 1]
251 pub fn match_path_old(path: &Path, segments: &[&str]) -> bool {
252 path.segments.iter().rev().zip(segments.iter().rev()).all(|(a, b)| a.name == *b)
255 /// Match a `Path` against a slice of segment string literals, e.g.
259 /// match_path(path, &["std", "rt", "begin_unwind"])
261 pub fn match_path_ast(path: &ast::Path, segments: &[&str]) -> bool {
262 path.segments.iter().rev().zip(segments.iter().rev()).all(|(a, b)| a.identifier.name == *b)
265 /// Get the definition associated to a path.
266 /// TODO: investigate if there is something more efficient for that.
267 pub fn path_to_def(cx: &LateContext, path: &[&str]) -> Option<def::Def> {
268 let cstore = &cx.tcx.sess.cstore;
270 let crates = cstore.crates();
271 let krate = crates.iter().find(|&&krate| cstore.crate_name(krate) == path[0]);
272 if let Some(krate) = krate {
275 index: CRATE_DEF_INDEX,
277 let mut items = cstore.item_children(krate);
278 let mut path_it = path.iter().skip(1).peekable();
281 let segment = match path_it.next() {
282 Some(segment) => segment,
286 for item in &mem::replace(&mut items, vec![]) {
287 if item.name == *segment {
288 if path_it.peek().is_none() {
289 return Some(item.def);
292 items = cstore.item_children(item.def.def_id());
302 /// Convenience function to get the `DefId` of a trait by path.
303 pub fn get_trait_def_id(cx: &LateContext, path: &[&str]) -> Option<DefId> {
304 let def = match path_to_def(cx, path) {
310 def::Def::Trait(trait_id) => Some(trait_id),
315 /// Check whether a type implements a trait.
316 /// See also `get_trait_def_id`.
317 pub fn implements_trait<'a, 'tcx>(
318 cx: &LateContext<'a, 'tcx>,
321 ty_params: Vec<ty::Ty<'tcx>>
323 cx.tcx.populate_implementations_for_trait_if_necessary(trait_id);
325 let ty = cx.tcx.erase_regions(&ty);
326 cx.tcx.infer_ctxt((), Reveal::All).enter(|infcx| {
327 let obligation = cx.tcx.predicate_for_trait_def(traits::ObligationCause::dummy(), trait_id, 0, ty, &ty_params);
329 traits::SelectionContext::new(&infcx).evaluate_obligation_conservatively(&obligation)
333 /// Resolve the definition of a node from its `NodeId`.
334 pub fn resolve_node(cx: &LateContext, qpath: &QPath, id: NodeId) -> def::Def {
335 cx.tables.qpath_def(qpath, id)
338 /// Match an `Expr` against a chain of methods, and return the matched `Expr`s.
340 /// For example, if `expr` represents the `.baz()` in `foo.bar().baz()`,
341 /// `matched_method_chain(expr, &["bar", "baz"])` will return a `Vec` containing the `Expr`s for
342 /// `.bar()` and `.baz()`
343 pub fn method_chain_args<'a>(expr: &'a Expr, methods: &[&str]) -> Option<Vec<&'a [Expr]>> {
344 let mut current = expr;
345 let mut matched = Vec::with_capacity(methods.len());
346 for method_name in methods.iter().rev() {
347 // method chains are stored last -> first
348 if let ExprMethodCall(ref name, _, ref args) = current.node {
349 if name.node == *method_name {
350 matched.push(&**args); // build up `matched` backwards
351 current = &args[0] // go to parent expression
359 matched.reverse(); // reverse `matched`, so that it is in the same order as `methods`
364 /// Get the name of the item the expression is in, if available.
365 pub fn get_item_name(cx: &LateContext, expr: &Expr) -> Option<Name> {
366 let parent_id = cx.tcx.map.get_parent(expr.id);
367 match cx.tcx.map.find(parent_id) {
368 Some(Node::NodeItem(&Item { ref name, .. })) |
369 Some(Node::NodeTraitItem(&TraitItem { ref name, .. })) |
370 Some(Node::NodeImplItem(&ImplItem { ref name, .. })) => Some(*name),
375 /// Convert a span to a code snippet if available, otherwise use default.
379 /// snippet(cx, expr.span, "..")
381 pub fn snippet<'a, 'b, T: LintContext<'b>>(cx: &T, span: Span, default: &'a str) -> Cow<'a, str> {
382 cx.sess().codemap().span_to_snippet(span).map(From::from).unwrap_or_else(|_| Cow::Borrowed(default))
385 /// Convert a span to a code snippet. Returns `None` if not available.
386 pub fn snippet_opt<'a, T: LintContext<'a>>(cx: &T, span: Span) -> Option<String> {
387 cx.sess().codemap().span_to_snippet(span).ok()
390 /// Convert a span (from a block) to a code snippet if available, otherwise use default.
391 /// This trims the code of indentation, except for the first line. Use it for blocks or block-like
392 /// things which need to be printed as such.
396 /// snippet(cx, expr.span, "..")
398 pub fn snippet_block<'a, 'b, T: LintContext<'b>>(cx: &T, span: Span, default: &'a str) -> Cow<'a, str> {
399 let snip = snippet(cx, span, default);
400 trim_multiline(snip, true)
403 /// Like `snippet_block`, but add braces if the expr is not an `ExprBlock`.
404 /// Also takes an `Option<String>` which can be put inside the braces.
405 pub fn expr_block<'a, 'b, T: LintContext<'b>>(
408 option: Option<String>,
411 let code = snippet_block(cx, expr.span, default);
412 let string = option.unwrap_or_default();
413 if let ExprBlock(_) = expr.node {
414 Cow::Owned(format!("{}{}", code, string))
415 } else if string.is_empty() {
416 Cow::Owned(format!("{{ {} }}", code))
418 Cow::Owned(format!("{{\n{};\n{}\n}}", code, string))
422 /// Trim indentation from a multiline string with possibility of ignoring the first line.
423 pub fn trim_multiline(s: Cow<str>, ignore_first: bool) -> Cow<str> {
424 let s_space = trim_multiline_inner(s, ignore_first, ' ');
425 let s_tab = trim_multiline_inner(s_space, ignore_first, '\t');
426 trim_multiline_inner(s_tab, ignore_first, ' ')
429 fn trim_multiline_inner(s: Cow<str>, ignore_first: bool, ch: char) -> Cow<str> {
431 .skip(ignore_first as usize)
436 // ignore empty lines
437 Some(l.char_indices()
438 .find(|&(_, x)| x != ch)
439 .unwrap_or((l.len(), ch))
448 .map(|(i, l)| if (ignore_first && i == 0) || l.is_empty() {
460 /// Get a parent expressions if any – this is useful to constrain a lint.
461 pub fn get_parent_expr<'c>(cx: &'c LateContext, e: &Expr) -> Option<&'c Expr> {
462 let map = &cx.tcx.map;
463 let node_id: NodeId = e.id;
464 let parent_id: NodeId = map.get_parent_node(node_id);
465 if node_id == parent_id {
468 map.find(parent_id).and_then(|node| if let Node::NodeExpr(parent) = node {
475 pub fn get_enclosing_block<'a, 'tcx: 'a>(cx: &LateContext<'a, 'tcx>, node: NodeId) -> Option<&'tcx Block> {
476 let map = &cx.tcx.map;
477 let enclosing_node = map.get_enclosing_scope(node)
478 .and_then(|enclosing_id| map.find(enclosing_id));
479 if let Some(node) = enclosing_node {
481 Node::NodeBlock(block) => Some(block),
482 Node::NodeItem(&Item { node: ItemFn(_, _, _, _, _, eid), .. }) => {
483 match cx.tcx.map.body(eid).value.node {
484 ExprBlock(ref block) => Some(block),
495 pub struct DiagnosticWrapper<'a>(pub DiagnosticBuilder<'a>);
497 impl<'a> Drop for DiagnosticWrapper<'a> {
503 impl<'a> DiagnosticWrapper<'a> {
504 fn wiki_link(&mut self, lint: &'static Lint) {
505 if env::var("CLIPPY_DISABLE_WIKI_LINKS").is_err() {
506 self.0.help(&format!("for further information visit https://github.com/Manishearth/rust-clippy/wiki#{}",
512 pub fn span_lint<'a, T: LintContext<'a>>(cx: &T, lint: &'static Lint, sp: Span, msg: &str) {
513 let mut db = DiagnosticWrapper(cx.struct_span_lint(lint, sp, msg));
514 if cx.current_level(lint) != Level::Allow {
519 pub fn span_help_and_lint<'a, 'tcx: 'a, T: LintContext<'tcx>>(
526 let mut db = DiagnosticWrapper(cx.struct_span_lint(lint, span, msg));
527 if cx.current_level(lint) != Level::Allow {
533 pub fn span_note_and_lint<'a, 'tcx: 'a, T: LintContext<'tcx>>(
541 let mut db = DiagnosticWrapper(cx.struct_span_lint(lint, span, msg));
542 if cx.current_level(lint) != Level::Allow {
543 if note_span == span {
546 db.0.span_note(note_span, note);
552 pub fn span_lint_and_then<'a, 'tcx: 'a, T: LintContext<'tcx>, F>(
558 ) where F: for<'b> FnOnce(&mut DiagnosticBuilder<'b>)
560 let mut db = DiagnosticWrapper(cx.struct_span_lint(lint, sp, msg));
561 if cx.current_level(lint) != Level::Allow {
567 /// Create a suggestion made from several `span → replacement`.
569 /// Note: in the JSON format (used by `compiletest_rs`), the help message will appear once per
570 /// replacement. In human-readable format though, it only appears once before the whole suggestion.
571 pub fn multispan_sugg(db: &mut DiagnosticBuilder, help_msg: String, sugg: &[(Span, &str)]) {
572 let sugg = rustc_errors::RenderSpan::Suggestion(rustc_errors::CodeSuggestion {
573 msp: MultiSpan::from_spans(sugg.iter().map(|&(span, _)| span).collect()),
574 substitutes: sugg.iter().map(|&(_, subs)| subs.to_owned()).collect(),
577 let sub = rustc_errors::SubDiagnostic {
578 level: rustc_errors::Level::Help,
579 message: vec![(help_msg, rustc_errors::snippet::Style::LabelPrimary)],
580 span: MultiSpan::new(),
581 render_span: Some(sugg),
583 db.children.push(sub);
586 /// Return the base type for references and raw pointers.
587 pub fn walk_ptrs_ty(ty: ty::Ty) -> ty::Ty {
589 ty::TyRef(_, ref tm) => walk_ptrs_ty(tm.ty),
594 /// Return the base type for references and raw pointers, and count reference depth.
595 pub fn walk_ptrs_ty_depth(ty: ty::Ty) -> (ty::Ty, usize) {
596 fn inner(ty: ty::Ty, depth: usize) -> (ty::Ty, usize) {
598 ty::TyRef(_, ref tm) => inner(tm.ty, depth + 1),
605 /// Check whether the given expression is a constant literal of the given value.
606 pub fn is_integer_literal(expr: &Expr, value: u128) -> bool {
607 // FIXME: use constant folding
608 if let ExprLit(ref spanned) = expr.node {
609 if let LitKind::Int(v, _) = spanned.node {
616 pub fn is_adjusted(cx: &LateContext, e: &Expr) -> bool {
617 cx.tables.adjustments.get(&e.id).is_some()
620 pub struct LimitStack {
624 impl Drop for LimitStack {
626 assert_eq!(self.stack.len(), 1);
631 pub fn new(limit: u64) -> LimitStack {
632 LimitStack { stack: vec![limit] }
634 pub fn limit(&self) -> u64 {
635 *self.stack.last().expect("there should always be a value in the stack")
637 pub fn push_attrs(&mut self, sess: &Session, attrs: &[ast::Attribute], name: &'static str) {
638 let stack = &mut self.stack;
639 parse_attrs(sess, attrs, name, |val| stack.push(val));
641 pub fn pop_attrs(&mut self, sess: &Session, attrs: &[ast::Attribute], name: &'static str) {
642 let stack = &mut self.stack;
643 parse_attrs(sess, attrs, name, |val| assert_eq!(stack.pop(), Some(val)));
647 fn parse_attrs<F: FnMut(u64)>(sess: &Session, attrs: &[ast::Attribute], name: &'static str, mut f: F) {
649 if attr.is_sugared_doc {
652 if let ast::MetaItemKind::NameValue(ref value) = attr.value.node {
653 if attr.name() == name {
654 if let LitKind::Str(ref s, _) = value.node {
655 if let Ok(value) = FromStr::from_str(&*s.as_str()) {
656 attr::mark_used(attr);
659 sess.span_err(value.span, "not a number");
669 /// Return the pre-expansion span if is this comes from an expansion of the macro `name`.
670 /// See also `is_direct_expn_of`.
671 pub fn is_expn_of(cx: &LateContext, mut span: Span, name: &str) -> Option<Span> {
673 let span_name_span = cx.tcx
676 .with_expn_info(span.expn_id, |expn| expn.map(|ei| (ei.callee.name(), ei.call_site)));
678 match span_name_span {
679 Some((mac_name, new_span)) if mac_name == name => return Some(new_span),
681 Some((_, new_span)) => span = new_span,
686 /// Return the pre-expansion span if is this directly comes from an expansion of the macro `name`.
687 /// The difference with `is_expn_of` is that in
691 /// `42` is considered expanded from `foo!` and `bar!` by `is_expn_of` but only `bar!` by
692 /// `is_direct_expn_of`.
693 pub fn is_direct_expn_of(cx: &LateContext, span: Span, name: &str) -> Option<Span> {
694 let span_name_span = cx.tcx
697 .with_expn_info(span.expn_id, |expn| expn.map(|ei| (ei.callee.name(), ei.call_site)));
699 match span_name_span {
700 Some((mac_name, new_span)) if mac_name == name => Some(new_span),
705 /// Return the index of the character after the first camel-case component of `s`.
706 pub fn camel_case_until(s: &str) -> usize {
707 let mut iter = s.char_indices();
708 if let Some((_, first)) = iter.next() {
709 if !first.is_uppercase() {
719 if c.is_lowercase() {
724 } else if c.is_uppercase() {
727 } else if !c.is_lowercase() {
731 if up { last_i } else { s.len() }
734 /// Return index of the last camel-case component of `s`.
735 pub fn camel_case_from(s: &str) -> usize {
736 let mut iter = s.char_indices().rev();
737 if let Some((_, first)) = iter.next() {
738 if !first.is_lowercase() {
745 let mut last_i = s.len();
748 if c.is_uppercase() {
751 } else if !c.is_lowercase() {
754 } else if c.is_lowercase() {
763 /// Convenience function to get the return type of a function
764 pub fn return_ty<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, fn_item: NodeId) -> ty::Ty<'tcx> {
765 let parameter_env = ty::ParameterEnvironment::for_item(cx.tcx, fn_item);
766 let fn_def_id = cx.tcx.map.local_def_id(fn_item);
767 let fn_sig = cx.tcx.item_type(fn_def_id).fn_sig();
768 let fn_sig = cx.tcx.liberate_late_bound_regions(parameter_env.free_id_outlive, fn_sig);
772 /// Check if two types are the same.
773 // FIXME: this works correctly for lifetimes bounds (`for <'a> Foo<'a>` == `for <'b> Foo<'b>` but
774 // not for type parameters.
775 pub fn same_tys<'a, 'tcx>(
776 cx: &LateContext<'a, 'tcx>,
779 parameter_item: NodeId
781 let parameter_env = ty::ParameterEnvironment::for_item(cx.tcx, parameter_item);
782 cx.tcx.infer_ctxt(parameter_env, Reveal::All).enter(|infcx| {
783 let new_a = a.subst(infcx.tcx, infcx.parameter_environment.free_substs);
784 let new_b = b.subst(infcx.tcx, infcx.parameter_environment.free_substs);
785 infcx.can_equate(&new_a, &new_b).is_ok()
789 /// Return whether the given type is an `unsafe` function.
790 pub fn type_is_unsafe_function(ty: ty::Ty) -> bool {
792 ty::TyFnDef(_, _, f) |
793 ty::TyFnPtr(f) => f.unsafety == Unsafety::Unsafe,
798 pub fn is_copy<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, ty: ty::Ty<'tcx>, env: NodeId) -> bool {
799 let env = ty::ParameterEnvironment::for_item(cx.tcx, env);
800 !ty.subst(cx.tcx, env.free_substs).moves_by_default(cx.tcx.global_tcx(), &env, DUMMY_SP)
803 /// Return whether a pattern is refutable.
804 pub fn is_refutable(cx: &LateContext, pat: &Pat) -> bool {
805 fn is_enum_variant(cx: &LateContext, qpath: &QPath, did: NodeId) -> bool {
806 matches!(cx.tables.qpath_def(qpath, did),
807 def::Def::Variant(..) | def::Def::VariantCtor(..))
810 fn are_refutable<'a, I: Iterator<Item = &'a Pat>>(cx: &LateContext, mut i: I) -> bool {
811 i.any(|pat| is_refutable(cx, pat))
815 PatKind::Binding(..) |
816 PatKind::Wild => false,
817 PatKind::Box(ref pat) |
818 PatKind::Ref(ref pat, _) => is_refutable(cx, pat),
820 PatKind::Range(..) => true,
821 PatKind::Path(ref qpath) => is_enum_variant(cx, qpath, pat.id),
822 PatKind::Tuple(ref pats, _) => are_refutable(cx, pats.iter().map(|pat| &**pat)),
823 PatKind::Struct(ref qpath, ref fields, _) => {
824 if is_enum_variant(cx, qpath, pat.id) {
827 are_refutable(cx, fields.iter().map(|field| &*field.node.pat))
830 PatKind::TupleStruct(ref qpath, ref pats, _) => {
831 if is_enum_variant(cx, qpath, pat.id) {
834 are_refutable(cx, pats.iter().map(|pat| &**pat))
837 PatKind::Slice(ref head, ref middle, ref tail) => {
838 are_refutable(cx, head.iter().chain(middle).chain(tail.iter()).map(|pat| &**pat))
843 /// Checks for the `#[automatically_derived]` attribute all `#[derive]`d implementations have.
844 pub fn is_automatically_derived(attrs: &[ast::Attribute]) -> bool {
845 attr::contains_name(attrs, "automatically_derived")
848 /// Remove blocks around an expression.
850 /// Ie. `x`, `{ x }` and `{{{{ x }}}}` all give `x`. `{ x; y }` and `{}` return themselves.
851 pub fn remove_blocks(expr: &Expr) -> &Expr {
852 if let ExprBlock(ref block) = expr.node {
853 if block.stmts.is_empty() {
854 if let Some(ref expr) = block.expr {
867 pub fn opt_def_id(def: Def) -> Option<DefId> {
873 Def::VariantCtor(id, ..) |
876 Def::AssociatedTy(id) |
879 Def::StructCtor(id, ..) |
884 Def::AssociatedConst(id) |
887 Def::Macro(id) => Some(id),
889 Def::Label(..) | Def::PrimTy(..) | Def::SelfTy(..) | Def::Err => None,
893 pub fn is_self(slf: &Arg) -> bool {
894 if let PatKind::Binding(_, _, name, _) = slf.pat.node {
895 name.node == keywords::SelfValue.name()
901 pub fn is_self_ty(slf: &Ty) -> bool {
903 let TyPath(ref qp) = slf.node,
904 let QPath::Resolved(None, ref path) = *qp,
905 let Def::SelfTy(..) = path.def,
912 pub fn iter_input_pats<'tcx>(decl: &FnDecl, body: &'tcx Body) -> impl Iterator<Item = &'tcx Arg> {
913 (0..decl.inputs.len()).map(move |i| &body.arguments[i])
916 /// Check if a given expression is a match expression
917 /// expanded from `?` operator or `try` macro.
918 pub fn is_try(expr: &Expr) -> Option<&Expr> {
919 fn is_ok(arm: &Arm) -> bool {
921 let PatKind::TupleStruct(ref path, ref pat, None) = arm.pats[0].node,
922 match_path(path, &paths::RESULT_OK[1..]),
923 let PatKind::Binding(_, defid, _, None) = pat[0].node,
924 let ExprPath(QPath::Resolved(None, ref path)) = arm.body.node,
925 path.def.def_id() == defid,
932 fn is_err(arm: &Arm) -> bool {
933 if let PatKind::TupleStruct(ref path, _, _) = arm.pats[0].node {
934 match_path(path, &paths::RESULT_ERR[1..])
940 if let ExprMatch(_, ref arms, ref source) = expr.node {
941 // desugared from a `?` operator
942 if let MatchSource::TryDesugar = *source {
948 arms[0].pats.len() == 1 && arms[0].guard.is_none(),
949 arms[1].pats.len() == 1 && arms[1].guard.is_none(),
950 (is_ok(&arms[0]) && is_err(&arms[1])) ||
951 (is_ok(&arms[1]) && is_err(&arms[0])),