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 rustc_span::hygiene::ExpnKind;
44 use smallvec::SmallVec;
45 use syntax::ast::{self, Attribute, LitKind};
47 use syntax::source_map::{Span, DUMMY_SP};
48 use syntax::symbol::{kw, Symbol};
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<'tcx>(path: &QPath<'tcx>) -> &'tcx PathSegment<'tcx> {
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<'tcx>(path: &QPath<'tcx>) -> Option<&'tcx PathSegment<'tcx>> {
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<'tcx>> {
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<'tcx>(
366 expr: &'tcx Expr<'tcx>,
368 ) -> (Vec<Symbol>, Vec<&'tcx [Expr<'tcx>]>, Vec<Span>) {
369 let mut method_names = Vec::with_capacity(max_depth);
370 let mut arg_lists = Vec::with_capacity(max_depth);
371 let mut spans = Vec::with_capacity(max_depth);
373 let mut current = expr;
374 for _ in 0..max_depth {
375 if let ExprKind::MethodCall(path, span, args) = ¤t.kind {
376 if args.iter().any(|e| e.span.from_expansion()) {
379 method_names.push(path.ident.name);
380 arg_lists.push(&**args);
388 (method_names, arg_lists, spans)
391 /// Matches an `Expr` against a chain of methods, and return the matched `Expr`s.
393 /// For example, if `expr` represents the `.baz()` in `foo.bar().baz()`,
394 /// `matched_method_chain(expr, &["bar", "baz"])` will return a `Vec`
395 /// containing the `Expr`s for
396 /// `.bar()` and `.baz()`
397 pub fn method_chain_args<'a>(expr: &'a Expr<'_>, methods: &[&str]) -> Option<Vec<&'a [Expr<'a>]>> {
398 let mut current = expr;
399 let mut matched = Vec::with_capacity(methods.len());
400 for method_name in methods.iter().rev() {
401 // method chains are stored last -> first
402 if let ExprKind::MethodCall(ref path, _, ref args) = current.kind {
403 if path.ident.name.as_str() == *method_name {
404 if args.iter().any(|e| e.span.from_expansion()) {
407 matched.push(&**args); // build up `matched` backwards
408 current = &args[0] // go to parent expression
416 // Reverse `matched` so that it is in the same order as `methods`.
421 /// Returns `true` if the provided `def_id` is an entrypoint to a program.
422 pub fn is_entrypoint_fn(cx: &LateContext<'_, '_>, def_id: DefId) -> bool {
424 .entry_fn(LOCAL_CRATE)
425 .map_or(false, |(entry_fn_def_id, _)| def_id == entry_fn_def_id)
428 /// Gets the name of the item the expression is in, if available.
429 pub fn get_item_name(cx: &LateContext<'_, '_>, expr: &Expr<'_>) -> Option<Name> {
430 let parent_id = cx.tcx.hir().get_parent_item(expr.hir_id);
431 match cx.tcx.hir().find(parent_id) {
432 Some(Node::Item(&Item { ref ident, .. })) => Some(ident.name),
433 Some(Node::TraitItem(&TraitItem { ident, .. })) | Some(Node::ImplItem(&ImplItem { ident, .. })) => {
440 /// Gets the name of a `Pat`, if any.
441 pub fn get_pat_name(pat: &Pat<'_>) -> Option<Name> {
443 PatKind::Binding(.., ref spname, _) => Some(spname.name),
444 PatKind::Path(ref qpath) => single_segment_path(qpath).map(|ps| ps.ident.name),
445 PatKind::Box(ref p) | PatKind::Ref(ref p, _) => get_pat_name(&*p),
450 struct ContainsName {
455 impl<'tcx> Visitor<'tcx> for ContainsName {
456 fn visit_name(&mut self, _: Span, name: Name) {
457 if self.name == name {
461 fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'tcx> {
462 NestedVisitorMap::None
466 /// Checks if an `Expr` contains a certain name.
467 pub fn contains_name(name: Name, expr: &Expr<'_>) -> bool {
468 let mut cn = ContainsName { name, result: false };
473 /// Converts a span to a code snippet if available, otherwise use default.
475 /// This is useful if you want to provide suggestions for your lint or more generally, if you want
476 /// to convert a given `Span` to a `str`.
480 /// snippet(cx, expr.span, "..")
482 pub fn snippet<'a, T: LintContext>(cx: &T, span: Span, default: &'a str) -> Cow<'a, str> {
483 snippet_opt(cx, span).map_or_else(|| Cow::Borrowed(default), From::from)
486 /// Same as `snippet`, but it adapts the applicability level by following rules:
488 /// - Applicability level `Unspecified` will never be changed.
489 /// - If the span is inside a macro, change the applicability level to `MaybeIncorrect`.
490 /// - If the default value is used and the applicability level is `MachineApplicable`, change it to
491 /// `HasPlaceholders`
492 pub fn snippet_with_applicability<'a, T: LintContext>(
496 applicability: &mut Applicability,
498 if *applicability != Applicability::Unspecified && span.from_expansion() {
499 *applicability = Applicability::MaybeIncorrect;
501 snippet_opt(cx, span).map_or_else(
503 if *applicability == Applicability::MachineApplicable {
504 *applicability = Applicability::HasPlaceholders;
506 Cow::Borrowed(default)
512 /// Same as `snippet`, but should only be used when it's clear that the input span is
513 /// not a macro argument.
514 pub fn snippet_with_macro_callsite<'a, T: LintContext>(cx: &T, span: Span, default: &'a str) -> Cow<'a, str> {
515 snippet(cx, span.source_callsite(), default)
518 /// Converts a span to a code snippet. Returns `None` if not available.
519 pub fn snippet_opt<T: LintContext>(cx: &T, span: Span) -> Option<String> {
520 cx.sess().source_map().span_to_snippet(span).ok()
523 /// Converts a span (from a block) to a code snippet if available, otherwise use
525 /// This trims the code of indentation, except for the first line. Use it for
526 /// blocks or block-like
527 /// things which need to be printed as such.
531 /// snippet_block(cx, expr.span, "..")
533 pub fn snippet_block<'a, T: LintContext>(cx: &T, span: Span, default: &'a str) -> Cow<'a, str> {
534 let snip = snippet(cx, span, default);
535 trim_multiline(snip, true)
538 /// Same as `snippet_block`, but adapts the applicability level by the rules of
539 /// `snippet_with_applicabiliy`.
540 pub fn snippet_block_with_applicability<'a, T: LintContext>(
544 applicability: &mut Applicability,
546 let snip = snippet_with_applicability(cx, span, default, applicability);
547 trim_multiline(snip, true)
550 /// Returns a new Span that covers the full last line of the given Span
551 pub fn last_line_of_span<T: LintContext>(cx: &T, span: Span) -> Span {
552 let source_map_and_line = cx.sess().source_map().lookup_line(span.lo()).unwrap();
553 let line_no = source_map_and_line.line;
554 let line_start = &source_map_and_line.sf.lines[line_no];
555 Span::new(*line_start, span.hi(), span.ctxt())
558 /// Like `snippet_block`, but add braces if the expr is not an `ExprKind::Block`.
559 /// Also takes an `Option<String>` which can be put inside the braces.
560 pub fn expr_block<'a, T: LintContext>(
563 option: Option<String>,
566 let code = snippet_block(cx, expr.span, default);
567 let string = option.unwrap_or_default();
568 if expr.span.from_expansion() {
569 Cow::Owned(format!("{{ {} }}", snippet_with_macro_callsite(cx, expr.span, default)))
570 } else if let ExprKind::Block(_, _) = expr.kind {
571 Cow::Owned(format!("{}{}", code, string))
572 } else if string.is_empty() {
573 Cow::Owned(format!("{{ {} }}", code))
575 Cow::Owned(format!("{{\n{};\n{}\n}}", code, string))
579 /// Trim indentation from a multiline string with possibility of ignoring the
581 pub fn trim_multiline(s: Cow<'_, str>, ignore_first: bool) -> Cow<'_, str> {
582 let s_space = trim_multiline_inner(s, ignore_first, ' ');
583 let s_tab = trim_multiline_inner(s_space, ignore_first, '\t');
584 trim_multiline_inner(s_tab, ignore_first, ' ')
587 fn trim_multiline_inner(s: Cow<'_, str>, ignore_first: bool, ch: char) -> Cow<'_, str> {
590 .skip(ignore_first as usize)
595 // ignore empty lines
596 Some(l.char_indices().find(|&(_, x)| x != ch).unwrap_or((l.len(), ch)).0)
606 if (ignore_first && i == 0) || l.is_empty() {
620 /// Gets the parent expression, if any –- this is useful to constrain a lint.
621 pub fn get_parent_expr<'c>(cx: &'c LateContext<'_, '_>, e: &Expr<'_>) -> Option<&'c Expr<'c>> {
622 let map = &cx.tcx.hir();
623 let hir_id = e.hir_id;
624 let parent_id = map.get_parent_node(hir_id);
625 if hir_id == parent_id {
628 map.find(parent_id).and_then(|node| {
629 if let Node::Expr(parent) = node {
637 pub fn get_enclosing_block<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, hir_id: HirId) -> Option<&'tcx Block<'tcx>> {
638 let map = &cx.tcx.hir();
639 let enclosing_node = map
640 .get_enclosing_scope(hir_id)
641 .and_then(|enclosing_id| map.find(enclosing_id));
642 if let Some(node) = enclosing_node {
644 Node::Block(block) => Some(block),
646 kind: ItemKind::Fn(_, _, eid),
649 | Node::ImplItem(&ImplItem {
650 kind: ImplItemKind::Method(_, eid),
652 }) => match cx.tcx.hir().body(eid).value.kind {
653 ExprKind::Block(ref block, _) => Some(block),
663 /// Returns the base type for HIR references and pointers.
664 pub fn walk_ptrs_hir_ty<'tcx>(ty: &'tcx hir::Ty<'tcx>) -> &'tcx hir::Ty<'tcx> {
666 TyKind::Ptr(ref mut_ty) | TyKind::Rptr(_, ref mut_ty) => walk_ptrs_hir_ty(&mut_ty.ty),
671 /// Returns the base type for references and raw pointers.
672 pub fn walk_ptrs_ty(ty: Ty<'_>) -> Ty<'_> {
674 ty::Ref(_, ty, _) => walk_ptrs_ty(ty),
679 /// Returns the base type for references and raw pointers, and count reference
681 pub fn walk_ptrs_ty_depth(ty: Ty<'_>) -> (Ty<'_>, usize) {
682 fn inner(ty: Ty<'_>, depth: usize) -> (Ty<'_>, usize) {
684 ty::Ref(_, ty, _) => inner(ty, depth + 1),
691 /// Checks whether the given expression is a constant integer of the given value.
692 /// unlike `is_integer_literal`, this version does const folding
693 pub fn is_integer_const(cx: &LateContext<'_, '_>, e: &Expr<'_>, value: u128) -> bool {
694 if is_integer_literal(e, value) {
697 let map = cx.tcx.hir();
698 let parent_item = map.get_parent_item(e.hir_id);
699 if let Some((Constant::Int(v), _)) = map
700 .maybe_body_owned_by(parent_item)
701 .and_then(|body_id| constant(cx, cx.tcx.body_tables(body_id), e))
709 /// Checks whether the given expression is a constant literal of the given value.
710 pub fn is_integer_literal(expr: &Expr<'_>, value: u128) -> bool {
711 // FIXME: use constant folding
712 if let ExprKind::Lit(ref spanned) = expr.kind {
713 if let LitKind::Int(v, _) = spanned.node {
720 /// Returns `true` if the given `Expr` has been coerced before.
722 /// Examples of coercions can be found in the Nomicon at
723 /// <https://doc.rust-lang.org/nomicon/coercions.html>.
725 /// See `rustc::ty::adjustment::Adjustment` and `rustc_typeck::check::coercion` for more
726 /// information on adjustments and coercions.
727 pub fn is_adjusted(cx: &LateContext<'_, '_>, e: &Expr<'_>) -> bool {
728 cx.tables.adjustments().get(e.hir_id).is_some()
731 /// Returns the pre-expansion span if is this comes from an expansion of the
733 /// See also `is_direct_expn_of`.
735 pub fn is_expn_of(mut span: Span, name: &str) -> Option<Span> {
737 if span.from_expansion() {
738 let data = span.ctxt().outer_expn_data();
739 let mac_name = data.kind.descr();
740 let new_span = data.call_site;
742 if mac_name.as_str() == name {
743 return Some(new_span);
753 /// Returns the pre-expansion span if the span directly comes from an expansion
754 /// of the macro `name`.
755 /// The difference with `is_expn_of` is that in
759 /// `42` is considered expanded from `foo!` and `bar!` by `is_expn_of` but only
761 /// `is_direct_expn_of`.
763 pub fn is_direct_expn_of(span: Span, name: &str) -> Option<Span> {
764 if span.from_expansion() {
765 let data = span.ctxt().outer_expn_data();
766 let mac_name = data.kind.descr();
767 let new_span = data.call_site;
769 if mac_name.as_str() == name {
779 /// Convenience function to get the return type of a function.
780 pub fn return_ty<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, fn_item: hir::HirId) -> Ty<'tcx> {
781 let fn_def_id = cx.tcx.hir().local_def_id(fn_item);
782 let ret_ty = cx.tcx.fn_sig(fn_def_id).output();
783 cx.tcx.erase_late_bound_regions(&ret_ty)
786 /// Checks if two types are the same.
788 /// This discards any lifetime annotations, too.
790 // FIXME: this works correctly for lifetimes bounds (`for <'a> Foo<'a>` ==
791 // `for <'b> Foo<'b>`, but not for type parameters).
792 pub fn same_tys<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, a: Ty<'tcx>, b: Ty<'tcx>) -> bool {
793 let a = cx.tcx.erase_late_bound_regions(&Binder::bind(a));
794 let b = cx.tcx.erase_late_bound_regions(&Binder::bind(b));
797 .enter(|infcx| infcx.can_eq(cx.param_env, a, b).is_ok())
800 /// Returns `true` if the given type is an `unsafe` function.
801 pub fn type_is_unsafe_function<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, ty: Ty<'tcx>) -> bool {
803 ty::FnDef(..) | ty::FnPtr(_) => ty.fn_sig(cx.tcx).unsafety() == Unsafety::Unsafe,
808 pub fn is_copy<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, ty: Ty<'tcx>) -> bool {
809 ty.is_copy_modulo_regions(cx.tcx, cx.param_env, DUMMY_SP)
812 /// Checks if an expression is constructing a tuple-like enum variant or struct
813 pub fn is_ctor_or_promotable_const_function(cx: &LateContext<'_, '_>, expr: &Expr<'_>) -> bool {
814 if let ExprKind::Call(ref fun, _) = expr.kind {
815 if let ExprKind::Path(ref qp) = fun.kind {
816 let res = cx.tables.qpath_res(qp, fun.hir_id);
818 def::Res::Def(DefKind::Variant, ..) | Res::Def(DefKind::Ctor(..), _) => true,
819 def::Res::Def(_, def_id) => cx.tcx.is_promotable_const_fn(def_id),
827 /// Returns `true` if a pattern is refutable.
828 pub fn is_refutable(cx: &LateContext<'_, '_>, pat: &Pat<'_>) -> bool {
829 fn is_enum_variant(cx: &LateContext<'_, '_>, qpath: &QPath<'_>, id: HirId) -> bool {
831 cx.tables.qpath_res(qpath, id),
832 def::Res::Def(DefKind::Variant, ..) | Res::Def(DefKind::Ctor(def::CtorOf::Variant, _), _)
836 fn are_refutable<'a, I: Iterator<Item = &'a Pat<'a>>>(cx: &LateContext<'_, '_>, mut i: I) -> bool {
837 i.any(|pat| is_refutable(cx, pat))
841 PatKind::Binding(..) | PatKind::Wild => false,
842 PatKind::Box(ref pat) | PatKind::Ref(ref pat, _) => is_refutable(cx, pat),
843 PatKind::Lit(..) | PatKind::Range(..) => true,
844 PatKind::Path(ref qpath) => is_enum_variant(cx, qpath, pat.hir_id),
845 PatKind::Or(ref pats) | PatKind::Tuple(ref pats, _) => are_refutable(cx, pats.iter().map(|pat| &**pat)),
846 PatKind::Struct(ref qpath, ref fields, _) => {
847 if is_enum_variant(cx, qpath, pat.hir_id) {
850 are_refutable(cx, fields.iter().map(|field| &*field.pat))
853 PatKind::TupleStruct(ref qpath, ref pats, _) => {
854 if is_enum_variant(cx, qpath, pat.hir_id) {
857 are_refutable(cx, pats.iter().map(|pat| &**pat))
860 PatKind::Slice(ref head, ref middle, ref tail) => {
861 are_refutable(cx, head.iter().chain(middle).chain(tail.iter()).map(|pat| &**pat))
866 /// Checks for the `#[automatically_derived]` attribute all `#[derive]`d
867 /// implementations have.
868 pub fn is_automatically_derived(attrs: &[ast::Attribute]) -> bool {
869 attr::contains_name(attrs, sym!(automatically_derived))
872 /// Remove blocks around an expression.
874 /// Ie. `x`, `{ x }` and `{{{{ x }}}}` all give `x`. `{ x; y }` and `{}` return
876 pub fn remove_blocks<'tcx>(expr: &'tcx Expr<'tcx>) -> &'tcx Expr<'tcx> {
877 if let ExprKind::Block(ref block, _) = expr.kind {
878 if block.stmts.is_empty() {
879 if let Some(ref expr) = block.expr {
880 return remove_blocks(expr);
887 pub fn is_self(slf: &Param<'_>) -> bool {
888 if let PatKind::Binding(.., name, _) = slf.pat.kind {
889 name.name == kw::SelfLower
895 pub fn is_self_ty(slf: &hir::Ty<'_>) -> bool {
897 if let TyKind::Path(ref qp) = slf.kind;
898 if let QPath::Resolved(None, ref path) = *qp;
899 if let Res::SelfTy(..) = path.res;
907 pub fn iter_input_pats<'tcx>(decl: &FnDecl<'_>, body: &'tcx Body<'_>) -> impl Iterator<Item = &'tcx Param<'tcx>> {
908 (0..decl.inputs.len()).map(move |i| &body.params[i])
911 /// Checks if a given expression is a match expression expanded from the `?`
912 /// operator or the `try` macro.
913 pub fn is_try<'tcx>(expr: &'tcx Expr<'tcx>) -> Option<&'tcx Expr<'tcx>> {
914 fn is_ok(arm: &Arm<'_>) -> bool {
916 if let PatKind::TupleStruct(ref path, ref pat, None) = arm.pat.kind;
917 if match_qpath(path, &paths::RESULT_OK[1..]);
918 if let PatKind::Binding(_, hir_id, _, None) = pat[0].kind;
919 if let ExprKind::Path(QPath::Resolved(None, ref path)) = arm.body.kind;
920 if let Res::Local(lid) = path.res;
929 fn is_err(arm: &Arm<'_>) -> bool {
930 if let PatKind::TupleStruct(ref path, _, _) = arm.pat.kind {
931 match_qpath(path, &paths::RESULT_ERR[1..])
937 if let ExprKind::Match(_, ref arms, ref source) = expr.kind {
938 // desugared from a `?` operator
939 if let MatchSource::TryDesugar = *source {
945 if arms[0].guard.is_none();
946 if arms[1].guard.is_none();
947 if (is_ok(&arms[0]) && is_err(&arms[1])) ||
948 (is_ok(&arms[1]) && is_err(&arms[0]));
958 /// Returns `true` if the lint is allowed in the current context
960 /// Useful for skipping long running code when it's unnecessary
961 pub fn is_allowed(cx: &LateContext<'_, '_>, lint: &'static Lint, id: HirId) -> bool {
962 cx.tcx.lint_level_at_node(lint, id).0 == Level::Allow
965 pub fn get_arg_name(pat: &Pat<'_>) -> Option<ast::Name> {
967 PatKind::Binding(.., ident, None) => Some(ident.name),
968 PatKind::Ref(ref subpat, _) => get_arg_name(subpat),
973 pub fn int_bits(tcx: TyCtxt<'_>, ity: ast::IntTy) -> u64 {
974 layout::Integer::from_attr(&tcx, attr::IntType::SignedInt(ity))
979 #[allow(clippy::cast_possible_wrap)]
980 /// Turn a constant int byte representation into an i128
981 pub fn sext(tcx: TyCtxt<'_>, u: u128, ity: ast::IntTy) -> i128 {
982 let amt = 128 - int_bits(tcx, ity);
983 ((u as i128) << amt) >> amt
986 #[allow(clippy::cast_sign_loss)]
987 /// clip unused bytes
988 pub fn unsext(tcx: TyCtxt<'_>, u: i128, ity: ast::IntTy) -> u128 {
989 let amt = 128 - int_bits(tcx, ity);
990 ((u as u128) << amt) >> amt
993 /// clip unused bytes
994 pub fn clip(tcx: TyCtxt<'_>, u: u128, ity: ast::UintTy) -> u128 {
995 let bits = layout::Integer::from_attr(&tcx, attr::IntType::UnsignedInt(ity))
998 let amt = 128 - bits;
1002 /// Removes block comments from the given `Vec` of lines.
1007 /// without_block_comments(vec!["/*", "foo", "*/"]);
1010 /// without_block_comments(vec!["bar", "/*", "foo", "*/"]);
1011 /// // => vec!["bar"]
1013 pub fn without_block_comments(lines: Vec<&str>) -> Vec<&str> {
1014 let mut without = vec![];
1016 let mut nest_level = 0;
1019 if line.contains("/*") {
1022 } else if line.contains("*/") {
1027 if nest_level == 0 {
1035 pub fn any_parent_is_automatically_derived(tcx: TyCtxt<'_>, node: HirId) -> bool {
1036 let map = &tcx.hir();
1037 let mut prev_enclosing_node = None;
1038 let mut enclosing_node = node;
1039 while Some(enclosing_node) != prev_enclosing_node {
1040 if is_automatically_derived(map.attrs(enclosing_node)) {
1043 prev_enclosing_node = Some(enclosing_node);
1044 enclosing_node = map.get_parent_item(enclosing_node);
1049 /// Returns true if ty has `iter` or `iter_mut` methods
1050 pub fn has_iter_method(cx: &LateContext<'_, '_>, probably_ref_ty: Ty<'_>) -> Option<&'static str> {
1051 // FIXME: instead of this hard-coded list, we should check if `<adt>::iter`
1052 // exists and has the desired signature. Unfortunately FnCtxt is not exported
1053 // so we can't use its `lookup_method` method.
1054 let into_iter_collections: [&[&str]; 13] = [
1061 &paths::LINKED_LIST,
1062 &paths::BINARY_HEAP,
1070 let ty_to_check = match probably_ref_ty.kind {
1071 ty::Ref(_, ty_to_check, _) => ty_to_check,
1072 _ => probably_ref_ty,
1075 let def_id = match ty_to_check.kind {
1076 ty::Array(..) => return Some("array"),
1077 ty::Slice(..) => return Some("slice"),
1078 ty::Adt(adt, _) => adt.did,
1082 for path in &into_iter_collections {
1083 if match_def_path(cx, def_id, path) {
1084 return Some(*path.last().unwrap());
1090 /// Matches a function call with the given path and returns the arguments.
1095 /// if let Some(args) = match_function_call(cx, begin_panic_call, &paths::BEGIN_PANIC);
1097 pub fn match_function_call<'a, 'tcx>(
1098 cx: &LateContext<'a, 'tcx>,
1099 expr: &'tcx Expr<'_>,
1101 ) -> Option<&'tcx [Expr<'tcx>]> {
1103 if let ExprKind::Call(ref fun, ref args) = expr.kind;
1104 if let ExprKind::Path(ref qpath) = fun.kind;
1105 if let Some(fun_def_id) = cx.tables.qpath_res(qpath, fun.hir_id).opt_def_id();
1106 if match_def_path(cx, fun_def_id, path);
1116 use super::{trim_multiline, without_block_comments};
1119 fn test_trim_multiline_single_line() {
1120 assert_eq!("", trim_multiline("".into(), false));
1121 assert_eq!("...", trim_multiline("...".into(), false));
1122 assert_eq!("...", trim_multiline(" ...".into(), false));
1123 assert_eq!("...", trim_multiline("\t...".into(), false));
1124 assert_eq!("...", trim_multiline("\t\t...".into(), false));
1129 fn test_trim_multiline_block() {
1135 }", trim_multiline(" if x {
1145 }", trim_multiline(" if x {
1154 fn test_trim_multiline_empty_line() {
1161 }", trim_multiline(" if x {
1170 fn test_without_block_comments_lines_without_block_comments() {
1171 let result = without_block_comments(vec!["/*", "", "*/"]);
1172 println!("result: {:?}", result);
1173 assert!(result.is_empty());
1175 let result = without_block_comments(vec!["", "/*", "", "*/", "#[crate_type = \"lib\"]", "/*", "", "*/", ""]);
1176 assert_eq!(result, vec!["", "#[crate_type = \"lib\"]", ""]);
1178 let result = without_block_comments(vec!["/* rust", "", "*/"]);
1179 assert!(result.is_empty());
1181 let result = without_block_comments(vec!["/* one-line comment */"]);
1182 assert!(result.is_empty());
1184 let result = without_block_comments(vec!["/* nested", "/* multi-line", "comment", "*/", "test", "*/"]);
1185 assert!(result.is_empty());
1187 let result = without_block_comments(vec!["/* nested /* inline /* comment */ test */ */"]);
1188 assert!(result.is_empty());
1190 let result = without_block_comments(vec!["foo", "bar", "baz"]);
1191 assert_eq!(result, vec!["foo", "bar", "baz"]);
1195 pub fn match_def_path<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, did: DefId, syms: &[&str]) -> bool {
1196 let path = cx.get_def_path(did);
1197 path.len() == syms.len() && path.into_iter().zip(syms.iter()).all(|(a, &b)| a.as_str() == b)
1200 /// Returns the list of condition expressions and the list of blocks in a
1201 /// sequence of `if/else`.
1202 /// E.g., this returns `([a, b], [c, d, e])` for the expression
1203 /// `if a { c } else if b { d } else { e }`.
1204 pub fn if_sequence<'tcx>(
1205 mut expr: &'tcx Expr<'tcx>,
1206 ) -> (SmallVec<[&'tcx Expr<'tcx>; 1]>, SmallVec<[&'tcx Block<'tcx>; 1]>) {
1207 let mut conds = SmallVec::new();
1208 let mut blocks: SmallVec<[&Block<'_>; 1]> = SmallVec::new();
1210 while let Some((ref cond, ref then_expr, ref else_expr)) = higher::if_block(&expr) {
1211 conds.push(&**cond);
1212 if let ExprKind::Block(ref block, _) = then_expr.kind {
1215 panic!("ExprKind::If node is not an ExprKind::Block");
1218 if let Some(ref else_expr) = *else_expr {
1225 // final `else {..}`
1226 if !blocks.is_empty() {
1227 if let ExprKind::Block(ref block, _) = expr.kind {
1228 blocks.push(&**block);
1235 pub fn parent_node_is_if_expr<'a, 'b>(expr: &Expr<'_>, cx: &LateContext<'a, 'b>) -> bool {
1236 let map = cx.tcx.hir();
1237 let parent_id = map.get_parent_node(expr.hir_id);
1238 let parent_node = map.get(parent_id);
1241 Node::Expr(e) => higher::if_block(&e).is_some(),
1242 Node::Arm(e) => higher::if_block(&e.body).is_some(),
1247 pub fn must_use_attr(attrs: &[Attribute]) -> Option<&Attribute> {
1248 attrs.iter().find(|attr| {
1249 attr.ident().map_or(false, |ident| {
1250 let ident: &str = &ident.as_str();
1256 // Returns whether the type has #[must_use] attribute
1257 pub fn is_must_use_ty<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, ty: Ty<'tcx>) -> bool {
1260 Adt(ref adt, _) => must_use_attr(&cx.tcx.get_attrs(adt.did)).is_some(),
1261 Foreign(ref did) => must_use_attr(&cx.tcx.get_attrs(*did)).is_some(),
1262 Slice(ref ty) | Array(ref ty, _) | RawPtr(ty::TypeAndMut { ref ty, .. }) | Ref(_, ref ty, _) => {
1263 // for the Array case we don't need to care for the len == 0 case
1264 // because we don't want to lint functions returning empty arrays
1265 is_must_use_ty(cx, *ty)
1267 Tuple(ref substs) => substs.types().any(|ty| is_must_use_ty(cx, ty)),
1268 Opaque(ref def_id, _) => {
1269 for (predicate, _) in cx.tcx.predicates_of(*def_id).predicates {
1270 if let ty::Predicate::Trait(ref poly_trait_predicate) = predicate {
1271 if must_use_attr(&cx.tcx.get_attrs(poly_trait_predicate.skip_binder().trait_ref.def_id)).is_some() {
1278 Dynamic(binder, _) => {
1279 for predicate in binder.skip_binder().iter() {
1280 if let ty::ExistentialPredicate::Trait(ref trait_ref) = predicate {
1281 if must_use_attr(&cx.tcx.get_attrs(trait_ref.def_id)).is_some() {
1292 // check if expr is calling method or function with #[must_use] attribyte
1293 pub fn is_must_use_func_call(cx: &LateContext<'_, '_>, expr: &Expr<'_>) -> bool {
1294 let did = match expr.kind {
1295 ExprKind::Call(ref path, _) => if_chain! {
1296 if let ExprKind::Path(ref qpath) = path.kind;
1297 if let def::Res::Def(_, did) = cx.tables.qpath_res(qpath, path.hir_id);
1304 ExprKind::MethodCall(_, _, _) => cx.tables.type_dependent_def_id(expr.hir_id),
1308 if let Some(did) = did {
1309 must_use_attr(&cx.tcx.get_attrs(did)).is_some()