14 pub mod internal_lints;
19 pub use self::attrs::*;
20 pub use self::diagnostics::*;
21 pub use self::hir_utils::{SpanlessEq, SpanlessHash};
26 use if_chain::if_chain;
29 use rustc::hir::def::{DefKind, Res};
30 use rustc::hir::def_id::{DefId, CRATE_DEF_INDEX, LOCAL_CRATE};
31 use rustc::hir::intravisit::{NestedVisitorMap, Visitor};
34 use rustc::lint::{LateContext, Level, Lint, LintContext};
38 layout::{self, IntegerExt},
42 use rustc_errors::Applicability;
43 use smallvec::SmallVec;
44 use syntax::ast::{self, LitKind};
46 use syntax::source_map::{Span, DUMMY_SP};
47 use syntax::symbol::{kw, Symbol};
48 use syntax_pos::hygiene::ExpnKind;
50 use crate::consts::{constant, Constant};
51 use crate::reexport::*;
53 /// Returns `true` if the two spans come from differing expansions (i.e., one is
54 /// from a macro and one isn't).
56 pub fn differing_macro_contexts(lhs: Span, rhs: Span) -> bool {
57 rhs.ctxt() != lhs.ctxt()
60 /// Returns `true` if the given `NodeId` is inside a constant context
65 /// if in_constant(cx, expr.hir_id) {
69 pub fn in_constant(cx: &LateContext<'_, '_>, id: HirId) -> bool {
70 let parent_id = cx.tcx.hir().get_parent_item(id);
71 match cx.tcx.hir().get(parent_id) {
73 kind: ItemKind::Const(..),
76 | Node::TraitItem(&TraitItem {
77 kind: TraitItemKind::Const(..),
80 | Node::ImplItem(&ImplItem {
81 kind: ImplItemKind::Const(..),
86 kind: ItemKind::Static(..),
90 kind: ItemKind::Fn(ref sig, ..),
93 | Node::ImplItem(&ImplItem {
94 kind: ImplItemKind::Method(ref sig, _),
96 }) => sig.header.constness == Constness::Const,
101 /// Returns `true` if this `span` was expanded by any macro.
103 pub fn in_macro(span: Span) -> bool {
104 if span.from_expansion() {
105 if let ExpnKind::Desugaring(..) = span.ctxt().outer_expn_data().kind {
114 // If the snippet is empty, it's an attribute that was inserted during macro
115 // expansion and we want to ignore those, because they could come from external
116 // sources that the user has no control over.
117 // For some reason these attributes don't have any expansion info on them, so
118 // we have to check it this way until there is a better way.
119 pub fn is_present_in_source<T: LintContext>(cx: &T, span: Span) -> bool {
120 if let Some(snippet) = snippet_opt(cx, span) {
121 if snippet.is_empty() {
128 /// Checks if type is struct, enum or union type with the given def path.
129 pub fn match_type(cx: &LateContext<'_, '_>, ty: Ty<'_>, path: &[&str]) -> bool {
131 ty::Adt(adt, _) => match_def_path(cx, adt.did, path),
136 /// Checks if the type is equal to a diagnostic item
137 pub fn is_type_diagnostic_item(cx: &LateContext<'_, '_>, ty: Ty<'_>, diag_item: Symbol) -> bool {
139 ty::Adt(adt, _) => cx.tcx.is_diagnostic_item(diag_item, adt.did),
144 /// Checks if the method call given in `expr` belongs to the given trait.
145 pub fn match_trait_method(cx: &LateContext<'_, '_>, expr: &Expr, path: &[&str]) -> bool {
146 let def_id = cx.tables.type_dependent_def_id(expr.hir_id).unwrap();
147 let trt_id = cx.tcx.trait_of_item(def_id);
148 if let Some(trt_id) = trt_id {
149 match_def_path(cx, trt_id, path)
155 /// Checks if an expression references a variable of the given name.
156 pub fn match_var(expr: &Expr, var: Name) -> bool {
157 if let ExprKind::Path(QPath::Resolved(None, ref path)) = expr.kind {
158 if path.segments.len() == 1 && path.segments[0].ident.name == var {
165 pub fn last_path_segment(path: &QPath) -> &PathSegment {
167 QPath::Resolved(_, ref path) => path.segments.last().expect("A path must have at least one segment"),
168 QPath::TypeRelative(_, ref seg) => seg,
172 pub fn single_segment_path(path: &QPath) -> Option<&PathSegment> {
174 QPath::Resolved(_, ref path) if path.segments.len() == 1 => Some(&path.segments[0]),
175 QPath::Resolved(..) => None,
176 QPath::TypeRelative(_, ref seg) => Some(seg),
180 /// Matches a `QPath` against a slice of segment string literals.
182 /// There is also `match_path` if you are dealing with a `rustc::hir::Path` instead of a
183 /// `rustc::hir::QPath`.
187 /// match_qpath(path, &["std", "rt", "begin_unwind"])
189 pub fn match_qpath(path: &QPath, segments: &[&str]) -> bool {
191 QPath::Resolved(_, ref path) => match_path(path, segments),
192 QPath::TypeRelative(ref ty, ref segment) => match ty.kind {
193 TyKind::Path(ref inner_path) => {
195 && match_qpath(inner_path, &segments[..(segments.len() - 1)])
196 && segment.ident.name.as_str() == segments[segments.len() - 1]
203 /// Matches a `Path` against a slice of segment string literals.
205 /// There is also `match_qpath` if you are dealing with a `rustc::hir::QPath` instead of a
206 /// `rustc::hir::Path`.
211 /// if match_path(&trait_ref.path, &paths::HASH) {
212 /// // This is the `std::hash::Hash` trait.
215 /// if match_path(ty_path, &["rustc", "lint", "Lint"]) {
216 /// // This is a `rustc::lint::Lint`.
219 pub fn match_path(path: &Path, segments: &[&str]) -> bool {
223 .zip(segments.iter().rev())
224 .all(|(a, b)| a.ident.name.as_str() == *b)
227 /// Matches a `Path` against a slice of segment string literals, e.g.
231 /// match_qpath(path, &["std", "rt", "begin_unwind"])
233 pub fn match_path_ast(path: &ast::Path, segments: &[&str]) -> bool {
237 .zip(segments.iter().rev())
238 .all(|(a, b)| a.ident.name.as_str() == *b)
241 /// Gets the definition associated to a path.
242 pub fn path_to_res(cx: &LateContext<'_, '_>, path: &[&str]) -> Option<def::Res> {
243 let crates = cx.tcx.crates();
246 .find(|&&krate| cx.tcx.crate_name(krate).as_str() == path[0]);
247 if let Some(krate) = krate {
250 index: CRATE_DEF_INDEX,
252 let mut items = cx.tcx.item_children(krate);
253 let mut path_it = path.iter().skip(1).peekable();
256 let segment = match path_it.next() {
257 Some(segment) => segment,
261 let result = SmallVec::<[_; 8]>::new();
262 for item in mem::replace(&mut items, cx.tcx.arena.alloc_slice(&result)).iter() {
263 if item.ident.name.as_str() == *segment {
264 if path_it.peek().is_none() {
265 return Some(item.res);
268 items = cx.tcx.item_children(item.res.def_id());
278 pub fn qpath_res(cx: &LateContext<'_, '_>, qpath: &hir::QPath, id: hir::HirId) -> Res {
280 hir::QPath::Resolved(_, path) => path.res,
281 hir::QPath::TypeRelative(..) => {
282 if cx.tcx.has_typeck_tables(id.owner_def_id()) {
283 cx.tcx.typeck_tables_of(id.owner_def_id()).qpath_res(qpath, id)
291 /// Convenience function to get the `DefId` of a trait by path.
292 /// It could be a trait or trait alias.
293 pub fn get_trait_def_id(cx: &LateContext<'_, '_>, path: &[&str]) -> Option<DefId> {
294 let res = match path_to_res(cx, path) {
300 Res::Def(DefKind::Trait, trait_id) | Res::Def(DefKind::TraitAlias, trait_id) => Some(trait_id),
301 Res::Err => unreachable!("this trait resolution is impossible: {:?}", &path),
306 /// Checks whether a type implements a trait.
307 /// See also `get_trait_def_id`.
308 pub fn implements_trait<'a, 'tcx>(
309 cx: &LateContext<'a, 'tcx>,
312 ty_params: &[GenericArg<'tcx>],
314 let ty = cx.tcx.erase_regions(&ty);
315 let obligation = cx.tcx.predicate_for_trait_def(
317 traits::ObligationCause::dummy(),
325 .enter(|infcx| infcx.predicate_must_hold_modulo_regions(&obligation))
328 /// Gets the `hir::TraitRef` of the trait the given method is implemented for.
330 /// Use this if you want to find the `TraitRef` of the `Add` trait in this example:
333 /// struct Point(isize, isize);
335 /// impl std::ops::Add for Point {
336 /// type Output = Self;
338 /// fn add(self, other: Self) -> Self {
343 pub fn trait_ref_of_method<'tcx>(cx: &LateContext<'_, 'tcx>, hir_id: HirId) -> Option<&'tcx TraitRef> {
344 // Get the implemented trait for the current function
345 let parent_impl = cx.tcx.hir().get_parent_item(hir_id);
347 if parent_impl != hir::CRATE_HIR_ID;
348 if let hir::Node::Item(item) = cx.tcx.hir().get(parent_impl);
349 if let hir::ItemKind::Impl(_, _, _, _, trait_ref, _, _) = &item.kind;
350 then { return trait_ref.as_ref(); }
355 /// Checks whether this type implements `Drop`.
356 pub fn has_drop<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, ty: Ty<'tcx>) -> bool {
357 match ty.ty_adt_def() {
358 Some(def) => def.has_dtor(cx.tcx),
363 /// Returns the method names and argument list of nested method call expressions that make up
364 /// `expr`. method/span lists are sorted with the most recent call first.
365 pub fn method_calls(expr: &Expr, max_depth: usize) -> (Vec<Symbol>, Vec<&[Expr]>, Vec<Span>) {
366 let mut method_names = Vec::with_capacity(max_depth);
367 let mut arg_lists = Vec::with_capacity(max_depth);
368 let mut spans = Vec::with_capacity(max_depth);
370 let mut current = expr;
371 for _ in 0..max_depth {
372 if let ExprKind::MethodCall(path, span, args) = ¤t.kind {
373 if args.iter().any(|e| e.span.from_expansion()) {
376 method_names.push(path.ident.name);
377 arg_lists.push(&**args);
385 (method_names, arg_lists, spans)
388 /// Matches an `Expr` against a chain of methods, and return the matched `Expr`s.
390 /// For example, if `expr` represents the `.baz()` in `foo.bar().baz()`,
391 /// `matched_method_chain(expr, &["bar", "baz"])` will return a `Vec`
392 /// containing the `Expr`s for
393 /// `.bar()` and `.baz()`
394 pub fn method_chain_args<'a>(expr: &'a Expr, methods: &[&str]) -> Option<Vec<&'a [Expr]>> {
395 let mut current = expr;
396 let mut matched = Vec::with_capacity(methods.len());
397 for method_name in methods.iter().rev() {
398 // method chains are stored last -> first
399 if let ExprKind::MethodCall(ref path, _, ref args) = current.kind {
400 if path.ident.name.as_str() == *method_name {
401 if args.iter().any(|e| e.span.from_expansion()) {
404 matched.push(&**args); // build up `matched` backwards
405 current = &args[0] // go to parent expression
413 // Reverse `matched` so that it is in the same order as `methods`.
418 /// Returns `true` if the provided `def_id` is an entrypoint to a program.
419 pub fn is_entrypoint_fn(cx: &LateContext<'_, '_>, def_id: DefId) -> bool {
421 .entry_fn(LOCAL_CRATE)
422 .map_or(false, |(entry_fn_def_id, _)| def_id == entry_fn_def_id)
425 /// Gets the name of the item the expression is in, if available.
426 pub fn get_item_name(cx: &LateContext<'_, '_>, expr: &Expr) -> Option<Name> {
427 let parent_id = cx.tcx.hir().get_parent_item(expr.hir_id);
428 match cx.tcx.hir().find(parent_id) {
429 Some(Node::Item(&Item { ref ident, .. })) => Some(ident.name),
430 Some(Node::TraitItem(&TraitItem { ident, .. })) | Some(Node::ImplItem(&ImplItem { ident, .. })) => {
437 /// Gets the name of a `Pat`, if any.
438 pub fn get_pat_name(pat: &Pat) -> Option<Name> {
440 PatKind::Binding(.., ref spname, _) => Some(spname.name),
441 PatKind::Path(ref qpath) => single_segment_path(qpath).map(|ps| ps.ident.name),
442 PatKind::Box(ref p) | PatKind::Ref(ref p, _) => get_pat_name(&*p),
447 struct ContainsName {
452 impl<'tcx> Visitor<'tcx> for ContainsName {
453 fn visit_name(&mut self, _: Span, name: Name) {
454 if self.name == name {
458 fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'tcx> {
459 NestedVisitorMap::None
463 /// Checks if an `Expr` contains a certain name.
464 pub fn contains_name(name: Name, expr: &Expr) -> bool {
465 let mut cn = ContainsName { name, result: false };
470 /// Converts a span to a code snippet if available, otherwise use default.
472 /// This is useful if you want to provide suggestions for your lint or more generally, if you want
473 /// to convert a given `Span` to a `str`.
477 /// snippet(cx, expr.span, "..")
479 pub fn snippet<'a, T: LintContext>(cx: &T, span: Span, default: &'a str) -> Cow<'a, str> {
480 snippet_opt(cx, span).map_or_else(|| Cow::Borrowed(default), From::from)
483 /// Same as `snippet`, but it adapts the applicability level by following rules:
485 /// - Applicability level `Unspecified` will never be changed.
486 /// - If the span is inside a macro, change the applicability level to `MaybeIncorrect`.
487 /// - If the default value is used and the applicability level is `MachineApplicable`, change it to
488 /// `HasPlaceholders`
489 pub fn snippet_with_applicability<'a, T: LintContext>(
493 applicability: &mut Applicability,
495 if *applicability != Applicability::Unspecified && span.from_expansion() {
496 *applicability = Applicability::MaybeIncorrect;
498 snippet_opt(cx, span).map_or_else(
500 if *applicability == Applicability::MachineApplicable {
501 *applicability = Applicability::HasPlaceholders;
503 Cow::Borrowed(default)
509 /// Same as `snippet`, but should only be used when it's clear that the input span is
510 /// not a macro argument.
511 pub fn snippet_with_macro_callsite<'a, T: LintContext>(cx: &T, span: Span, default: &'a str) -> Cow<'a, str> {
512 snippet(cx, span.source_callsite(), default)
515 /// Converts a span to a code snippet. Returns `None` if not available.
516 pub fn snippet_opt<T: LintContext>(cx: &T, span: Span) -> Option<String> {
517 cx.sess().source_map().span_to_snippet(span).ok()
520 /// Converts a span (from a block) to a code snippet if available, otherwise use
522 /// This trims the code of indentation, except for the first line. Use it for
523 /// blocks or block-like
524 /// things which need to be printed as such.
528 /// snippet_block(cx, expr.span, "..")
530 pub fn snippet_block<'a, T: LintContext>(cx: &T, span: Span, default: &'a str) -> Cow<'a, str> {
531 let snip = snippet(cx, span, default);
532 trim_multiline(snip, true)
535 /// Same as `snippet_block`, but adapts the applicability level by the rules of
536 /// `snippet_with_applicabiliy`.
537 pub fn snippet_block_with_applicability<'a, T: LintContext>(
541 applicability: &mut Applicability,
543 let snip = snippet_with_applicability(cx, span, default, applicability);
544 trim_multiline(snip, true)
547 /// Returns a new Span that covers the full last line of the given Span
548 pub fn last_line_of_span<T: LintContext>(cx: &T, span: Span) -> Span {
549 let source_map_and_line = cx.sess().source_map().lookup_line(span.lo()).unwrap();
550 let line_no = source_map_and_line.line;
551 let line_start = &source_map_and_line.sf.lines[line_no];
552 Span::new(*line_start, span.hi(), span.ctxt())
555 /// Like `snippet_block`, but add braces if the expr is not an `ExprKind::Block`.
556 /// Also takes an `Option<String>` which can be put inside the braces.
557 pub fn expr_block<'a, T: LintContext>(cx: &T, expr: &Expr, option: Option<String>, default: &'a str) -> Cow<'a, str> {
558 let code = snippet_block(cx, expr.span, default);
559 let string = option.unwrap_or_default();
560 if expr.span.from_expansion() {
561 Cow::Owned(format!("{{ {} }}", snippet_with_macro_callsite(cx, expr.span, default)))
562 } else if let ExprKind::Block(_, _) = expr.kind {
563 Cow::Owned(format!("{}{}", code, string))
564 } else if string.is_empty() {
565 Cow::Owned(format!("{{ {} }}", code))
567 Cow::Owned(format!("{{\n{};\n{}\n}}", code, string))
571 /// Trim indentation from a multiline string with possibility of ignoring the
573 pub fn trim_multiline(s: Cow<'_, str>, ignore_first: bool) -> Cow<'_, str> {
574 let s_space = trim_multiline_inner(s, ignore_first, ' ');
575 let s_tab = trim_multiline_inner(s_space, ignore_first, '\t');
576 trim_multiline_inner(s_tab, ignore_first, ' ')
579 fn trim_multiline_inner(s: Cow<'_, str>, ignore_first: bool, ch: char) -> Cow<'_, str> {
582 .skip(ignore_first as usize)
587 // ignore empty lines
588 Some(l.char_indices().find(|&(_, x)| x != ch).unwrap_or((l.len(), ch)).0)
598 if (ignore_first && i == 0) || l.is_empty() {
612 /// Gets the parent expression, if any –- this is useful to constrain a lint.
613 pub fn get_parent_expr<'c>(cx: &'c LateContext<'_, '_>, e: &Expr) -> Option<&'c Expr> {
614 let map = &cx.tcx.hir();
615 let hir_id = e.hir_id;
616 let parent_id = map.get_parent_node(hir_id);
617 if hir_id == parent_id {
620 map.find(parent_id).and_then(|node| {
621 if let Node::Expr(parent) = node {
629 pub fn get_enclosing_block<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, hir_id: HirId) -> Option<&'tcx Block> {
630 let map = &cx.tcx.hir();
631 let enclosing_node = map
632 .get_enclosing_scope(hir_id)
633 .and_then(|enclosing_id| map.find(enclosing_id));
634 if let Some(node) = enclosing_node {
636 Node::Block(block) => Some(block),
638 kind: ItemKind::Fn(_, _, eid),
641 | Node::ImplItem(&ImplItem {
642 kind: ImplItemKind::Method(_, eid),
644 }) => match cx.tcx.hir().body(eid).value.kind {
645 ExprKind::Block(ref block, _) => Some(block),
655 /// Returns the base type for HIR references and pointers.
656 pub fn walk_ptrs_hir_ty(ty: &hir::Ty) -> &hir::Ty {
658 TyKind::Ptr(ref mut_ty) | TyKind::Rptr(_, ref mut_ty) => walk_ptrs_hir_ty(&mut_ty.ty),
663 /// Returns the base type for references and raw pointers.
664 pub fn walk_ptrs_ty(ty: Ty<'_>) -> Ty<'_> {
666 ty::Ref(_, ty, _) => walk_ptrs_ty(ty),
671 /// Returns the base type for references and raw pointers, and count reference
673 pub fn walk_ptrs_ty_depth(ty: Ty<'_>) -> (Ty<'_>, usize) {
674 fn inner(ty: Ty<'_>, depth: usize) -> (Ty<'_>, usize) {
676 ty::Ref(_, ty, _) => inner(ty, depth + 1),
683 /// Checks whether the given expression is a constant integer of the given value.
684 /// unlike `is_integer_literal`, this version does const folding
685 pub fn is_integer_const(cx: &LateContext<'_, '_>, e: &Expr, value: u128) -> bool {
686 if is_integer_literal(e, value) {
689 let map = cx.tcx.hir();
690 let parent_item = map.get_parent_item(e.hir_id);
691 if let Some((Constant::Int(v), _)) = map
692 .maybe_body_owned_by(parent_item)
693 .and_then(|body_id| constant(cx, cx.tcx.body_tables(body_id), e))
701 /// Checks whether the given expression is a constant literal of the given value.
702 pub fn is_integer_literal(expr: &Expr, value: u128) -> bool {
703 // FIXME: use constant folding
704 if let ExprKind::Lit(ref spanned) = expr.kind {
705 if let LitKind::Int(v, _) = spanned.node {
712 /// Returns `true` if the given `Expr` has been coerced before.
714 /// Examples of coercions can be found in the Nomicon at
715 /// <https://doc.rust-lang.org/nomicon/coercions.html>.
717 /// See `rustc::ty::adjustment::Adjustment` and `rustc_typeck::check::coercion` for more
718 /// information on adjustments and coercions.
719 pub fn is_adjusted(cx: &LateContext<'_, '_>, e: &Expr) -> bool {
720 cx.tables.adjustments().get(e.hir_id).is_some()
723 /// Returns the pre-expansion span if is this comes from an expansion of the
725 /// See also `is_direct_expn_of`.
727 pub fn is_expn_of(mut span: Span, name: &str) -> Option<Span> {
729 if span.from_expansion() {
730 let data = span.ctxt().outer_expn_data();
731 let mac_name = data.kind.descr();
732 let new_span = data.call_site;
734 if mac_name.as_str() == name {
735 return Some(new_span);
745 /// Returns the pre-expansion span if the span directly comes from an expansion
746 /// of the macro `name`.
747 /// The difference with `is_expn_of` is that in
751 /// `42` is considered expanded from `foo!` and `bar!` by `is_expn_of` but only
753 /// `is_direct_expn_of`.
755 pub fn is_direct_expn_of(span: Span, name: &str) -> Option<Span> {
756 if span.from_expansion() {
757 let data = span.ctxt().outer_expn_data();
758 let mac_name = data.kind.descr();
759 let new_span = data.call_site;
761 if mac_name.as_str() == name {
771 /// Convenience function to get the return type of a function.
772 pub fn return_ty<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, fn_item: hir::HirId) -> Ty<'tcx> {
773 let fn_def_id = cx.tcx.hir().local_def_id(fn_item);
774 let ret_ty = cx.tcx.fn_sig(fn_def_id).output();
775 cx.tcx.erase_late_bound_regions(&ret_ty)
778 /// Checks if two types are the same.
780 /// This discards any lifetime annotations, too.
782 // FIXME: this works correctly for lifetimes bounds (`for <'a> Foo<'a>` ==
783 // `for <'b> Foo<'b>`, but not for type parameters).
784 pub fn same_tys<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, a: Ty<'tcx>, b: Ty<'tcx>) -> bool {
785 let a = cx.tcx.erase_late_bound_regions(&Binder::bind(a));
786 let b = cx.tcx.erase_late_bound_regions(&Binder::bind(b));
789 .enter(|infcx| infcx.can_eq(cx.param_env, a, b).is_ok())
792 /// Returns `true` if the given type is an `unsafe` function.
793 pub fn type_is_unsafe_function<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, ty: Ty<'tcx>) -> bool {
795 ty::FnDef(..) | ty::FnPtr(_) => ty.fn_sig(cx.tcx).unsafety() == Unsafety::Unsafe,
800 pub fn is_copy<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, ty: Ty<'tcx>) -> bool {
801 ty.is_copy_modulo_regions(cx.tcx, cx.param_env, DUMMY_SP)
804 /// Checks if an expression is constructing a tuple-like enum variant or struct
805 pub fn is_ctor_or_promotable_const_function(cx: &LateContext<'_, '_>, expr: &Expr) -> bool {
806 if let ExprKind::Call(ref fun, _) = expr.kind {
807 if let ExprKind::Path(ref qp) = fun.kind {
808 let res = cx.tables.qpath_res(qp, fun.hir_id);
810 def::Res::Def(DefKind::Variant, ..) | Res::Def(DefKind::Ctor(..), _) => true,
811 def::Res::Def(_, def_id) => cx.tcx.is_promotable_const_fn(def_id),
819 /// Returns `true` if a pattern is refutable.
820 pub fn is_refutable(cx: &LateContext<'_, '_>, pat: &Pat) -> bool {
821 fn is_enum_variant(cx: &LateContext<'_, '_>, qpath: &QPath, id: HirId) -> bool {
823 cx.tables.qpath_res(qpath, id),
824 def::Res::Def(DefKind::Variant, ..) | Res::Def(DefKind::Ctor(def::CtorOf::Variant, _), _)
828 fn are_refutable<'a, I: Iterator<Item = &'a Pat>>(cx: &LateContext<'_, '_>, mut i: I) -> bool {
829 i.any(|pat| is_refutable(cx, pat))
833 PatKind::Binding(..) | PatKind::Wild => false,
834 PatKind::Box(ref pat) | PatKind::Ref(ref pat, _) => is_refutable(cx, pat),
835 PatKind::Lit(..) | PatKind::Range(..) => true,
836 PatKind::Path(ref qpath) => is_enum_variant(cx, qpath, pat.hir_id),
837 PatKind::Or(ref pats) | PatKind::Tuple(ref pats, _) => are_refutable(cx, pats.iter().map(|pat| &**pat)),
838 PatKind::Struct(ref qpath, ref fields, _) => {
839 if is_enum_variant(cx, qpath, pat.hir_id) {
842 are_refutable(cx, fields.iter().map(|field| &*field.pat))
845 PatKind::TupleStruct(ref qpath, ref pats, _) => {
846 if is_enum_variant(cx, qpath, pat.hir_id) {
849 are_refutable(cx, pats.iter().map(|pat| &**pat))
852 PatKind::Slice(ref head, ref middle, ref tail) => {
853 are_refutable(cx, head.iter().chain(middle).chain(tail.iter()).map(|pat| &**pat))
858 /// Checks for the `#[automatically_derived]` attribute all `#[derive]`d
859 /// implementations have.
860 pub fn is_automatically_derived(attrs: &[ast::Attribute]) -> bool {
861 attr::contains_name(attrs, sym!(automatically_derived))
864 /// Remove blocks around an expression.
866 /// Ie. `x`, `{ x }` and `{{{{ x }}}}` all give `x`. `{ x; y }` and `{}` return
868 pub fn remove_blocks(expr: &Expr) -> &Expr {
869 if let ExprKind::Block(ref block, _) = expr.kind {
870 if block.stmts.is_empty() {
871 if let Some(ref expr) = block.expr {
884 pub fn is_self(slf: &Param) -> bool {
885 if let PatKind::Binding(.., name, _) = slf.pat.kind {
886 name.name == kw::SelfLower
892 pub fn is_self_ty(slf: &hir::Ty) -> bool {
894 if let TyKind::Path(ref qp) = slf.kind;
895 if let QPath::Resolved(None, ref path) = *qp;
896 if let Res::SelfTy(..) = path.res;
904 pub fn iter_input_pats<'tcx>(decl: &FnDecl, body: &'tcx Body) -> impl Iterator<Item = &'tcx Param> {
905 (0..decl.inputs.len()).map(move |i| &body.params[i])
908 /// Checks if a given expression is a match expression expanded from the `?`
909 /// operator or the `try` macro.
910 pub fn is_try(expr: &Expr) -> Option<&Expr> {
911 fn is_ok(arm: &Arm) -> bool {
913 if let PatKind::TupleStruct(ref path, ref pat, None) = arm.pat.kind;
914 if match_qpath(path, &paths::RESULT_OK[1..]);
915 if let PatKind::Binding(_, hir_id, _, None) = pat[0].kind;
916 if let ExprKind::Path(QPath::Resolved(None, ref path)) = arm.body.kind;
917 if let Res::Local(lid) = path.res;
926 fn is_err(arm: &Arm) -> bool {
927 if let PatKind::TupleStruct(ref path, _, _) = arm.pat.kind {
928 match_qpath(path, &paths::RESULT_ERR[1..])
934 if let ExprKind::Match(_, ref arms, ref source) = expr.kind {
935 // desugared from a `?` operator
936 if let MatchSource::TryDesugar = *source {
942 if arms[0].guard.is_none();
943 if arms[1].guard.is_none();
944 if (is_ok(&arms[0]) && is_err(&arms[1])) ||
945 (is_ok(&arms[1]) && is_err(&arms[0]));
955 /// Returns `true` if the lint is allowed in the current context
957 /// Useful for skipping long running code when it's unnecessary
958 pub fn is_allowed(cx: &LateContext<'_, '_>, lint: &'static Lint, id: HirId) -> bool {
959 cx.tcx.lint_level_at_node(lint, id).0 == Level::Allow
962 pub fn get_arg_name(pat: &Pat) -> Option<ast::Name> {
964 PatKind::Binding(.., ident, None) => Some(ident.name),
965 PatKind::Ref(ref subpat, _) => get_arg_name(subpat),
970 pub fn int_bits(tcx: TyCtxt<'_>, ity: ast::IntTy) -> u64 {
971 layout::Integer::from_attr(&tcx, attr::IntType::SignedInt(ity))
976 #[allow(clippy::cast_possible_wrap)]
977 /// Turn a constant int byte representation into an i128
978 pub fn sext(tcx: TyCtxt<'_>, u: u128, ity: ast::IntTy) -> i128 {
979 let amt = 128 - int_bits(tcx, ity);
980 ((u as i128) << amt) >> amt
983 #[allow(clippy::cast_sign_loss)]
984 /// clip unused bytes
985 pub fn unsext(tcx: TyCtxt<'_>, u: i128, ity: ast::IntTy) -> u128 {
986 let amt = 128 - int_bits(tcx, ity);
987 ((u as u128) << amt) >> amt
990 /// clip unused bytes
991 pub fn clip(tcx: TyCtxt<'_>, u: u128, ity: ast::UintTy) -> u128 {
992 let bits = layout::Integer::from_attr(&tcx, attr::IntType::UnsignedInt(ity))
995 let amt = 128 - bits;
999 /// Removes block comments from the given `Vec` of lines.
1004 /// without_block_comments(vec!["/*", "foo", "*/"]);
1007 /// without_block_comments(vec!["bar", "/*", "foo", "*/"]);
1008 /// // => vec!["bar"]
1010 pub fn without_block_comments(lines: Vec<&str>) -> Vec<&str> {
1011 let mut without = vec![];
1013 let mut nest_level = 0;
1016 if line.contains("/*") {
1019 } else if line.contains("*/") {
1024 if nest_level == 0 {
1032 pub fn any_parent_is_automatically_derived(tcx: TyCtxt<'_>, node: HirId) -> bool {
1033 let map = &tcx.hir();
1034 let mut prev_enclosing_node = None;
1035 let mut enclosing_node = node;
1036 while Some(enclosing_node) != prev_enclosing_node {
1037 if is_automatically_derived(map.attrs(enclosing_node)) {
1040 prev_enclosing_node = Some(enclosing_node);
1041 enclosing_node = map.get_parent_item(enclosing_node);
1046 /// Returns true if ty has `iter` or `iter_mut` methods
1047 pub fn has_iter_method(cx: &LateContext<'_, '_>, probably_ref_ty: Ty<'_>) -> Option<&'static str> {
1048 // FIXME: instead of this hard-coded list, we should check if `<adt>::iter`
1049 // exists and has the desired signature. Unfortunately FnCtxt is not exported
1050 // so we can't use its `lookup_method` method.
1051 let into_iter_collections: [&[&str]; 13] = [
1058 &paths::LINKED_LIST,
1059 &paths::BINARY_HEAP,
1067 let ty_to_check = match probably_ref_ty.kind {
1068 ty::Ref(_, ty_to_check, _) => ty_to_check,
1069 _ => probably_ref_ty,
1072 let def_id = match ty_to_check.kind {
1073 ty::Array(..) => return Some("array"),
1074 ty::Slice(..) => return Some("slice"),
1075 ty::Adt(adt, _) => adt.did,
1079 for path in &into_iter_collections {
1080 if match_def_path(cx, def_id, path) {
1081 return Some(*path.last().unwrap());
1087 /// Matches a function call with the given path and returns the arguments.
1092 /// if let Some(args) = match_function_call(cx, begin_panic_call, &paths::BEGIN_PANIC);
1094 pub fn match_function_call<'a, 'tcx>(
1095 cx: &LateContext<'a, 'tcx>,
1098 ) -> Option<&'tcx [Expr]> {
1100 if let ExprKind::Call(ref fun, ref args) = expr.kind;
1101 if let ExprKind::Path(ref qpath) = fun.kind;
1102 if let Some(fun_def_id) = cx.tables.qpath_res(qpath, fun.hir_id).opt_def_id();
1103 if match_def_path(cx, fun_def_id, path);
1113 use super::{trim_multiline, without_block_comments};
1116 fn test_trim_multiline_single_line() {
1117 assert_eq!("", trim_multiline("".into(), false));
1118 assert_eq!("...", trim_multiline("...".into(), false));
1119 assert_eq!("...", trim_multiline(" ...".into(), false));
1120 assert_eq!("...", trim_multiline("\t...".into(), false));
1121 assert_eq!("...", trim_multiline("\t\t...".into(), false));
1126 fn test_trim_multiline_block() {
1132 }", trim_multiline(" if x {
1142 }", trim_multiline(" if x {
1151 fn test_trim_multiline_empty_line() {
1158 }", trim_multiline(" if x {
1167 fn test_without_block_comments_lines_without_block_comments() {
1168 let result = without_block_comments(vec!["/*", "", "*/"]);
1169 println!("result: {:?}", result);
1170 assert!(result.is_empty());
1172 let result = without_block_comments(vec!["", "/*", "", "*/", "#[crate_type = \"lib\"]", "/*", "", "*/", ""]);
1173 assert_eq!(result, vec!["", "#[crate_type = \"lib\"]", ""]);
1175 let result = without_block_comments(vec!["/* rust", "", "*/"]);
1176 assert!(result.is_empty());
1178 let result = without_block_comments(vec!["/* one-line comment */"]);
1179 assert!(result.is_empty());
1181 let result = without_block_comments(vec!["/* nested", "/* multi-line", "comment", "*/", "test", "*/"]);
1182 assert!(result.is_empty());
1184 let result = without_block_comments(vec!["/* nested /* inline /* comment */ test */ */"]);
1185 assert!(result.is_empty());
1187 let result = without_block_comments(vec!["foo", "bar", "baz"]);
1188 assert_eq!(result, vec!["foo", "bar", "baz"]);
1192 pub fn match_def_path<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, did: DefId, syms: &[&str]) -> bool {
1193 let path = cx.get_def_path(did);
1194 path.len() == syms.len() && path.into_iter().zip(syms.iter()).all(|(a, &b)| a.as_str() == b)
1197 /// Returns the list of condition expressions and the list of blocks in a
1198 /// sequence of `if/else`.
1199 /// E.g., this returns `([a, b], [c, d, e])` for the expression
1200 /// `if a { c } else if b { d } else { e }`.
1201 pub fn if_sequence(mut expr: &Expr) -> (SmallVec<[&Expr; 1]>, SmallVec<[&Block; 1]>) {
1202 let mut conds = SmallVec::new();
1203 let mut blocks: SmallVec<[&Block; 1]> = SmallVec::new();
1205 while let Some((ref cond, ref then_expr, ref else_expr)) = higher::if_block(&expr) {
1206 conds.push(&**cond);
1207 if let ExprKind::Block(ref block, _) = then_expr.kind {
1210 panic!("ExprKind::If node is not an ExprKind::Block");
1213 if let Some(ref else_expr) = *else_expr {
1220 // final `else {..}`
1221 if !blocks.is_empty() {
1222 if let ExprKind::Block(ref block, _) = expr.kind {
1223 blocks.push(&**block);
1230 pub fn parent_node_is_if_expr<'a, 'b>(expr: &Expr, cx: &LateContext<'a, 'b>) -> bool {
1231 let parent_id = cx.tcx.hir().get_parent_node(expr.hir_id);
1232 let parent_node = cx.tcx.hir().get(parent_id);
1235 rustc::hir::Node::Expr(e) => higher::if_block(&e).is_some(),
1236 rustc::hir::Node::Arm(e) => higher::if_block(&e.body).is_some(),