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;
28 use rustc::hir::map::Map;
30 use rustc::traits::predicate_for_trait_def;
33 layout::{self, IntegerExt},
37 use rustc_errors::Applicability;
39 use rustc_hir::def::{DefKind, Res};
40 use rustc_hir::def_id::{DefId, CRATE_DEF_INDEX, LOCAL_CRATE};
41 use rustc_hir::intravisit::{NestedVisitorMap, Visitor};
44 use rustc_lint::{LateContext, Level, Lint, LintContext};
45 use rustc_span::hygiene::ExpnKind;
46 use rustc_span::symbol::{kw, Symbol};
47 use rustc_span::{BytePos, Pos, Span, DUMMY_SP};
48 use smallvec::SmallVec;
49 use syntax::ast::{self, Attribute, LitKind};
52 use crate::consts::{constant, Constant};
53 use crate::reexport::*;
55 /// Returns `true` if the two spans come from differing expansions (i.e., one is
56 /// from a macro and one isn't).
58 pub fn differing_macro_contexts(lhs: Span, rhs: Span) -> bool {
59 rhs.ctxt() != lhs.ctxt()
62 /// Returns `true` if the given `NodeId` is inside a constant context
67 /// if in_constant(cx, expr.hir_id) {
71 pub fn in_constant(cx: &LateContext<'_, '_>, id: HirId) -> bool {
72 let parent_id = cx.tcx.hir().get_parent_item(id);
73 match cx.tcx.hir().get(parent_id) {
75 kind: ItemKind::Const(..),
78 | Node::TraitItem(&TraitItem {
79 kind: TraitItemKind::Const(..),
82 | Node::ImplItem(&ImplItem {
83 kind: ImplItemKind::Const(..),
88 kind: ItemKind::Static(..),
92 kind: ItemKind::Fn(ref sig, ..),
95 | Node::ImplItem(&ImplItem {
96 kind: ImplItemKind::Method(ref sig, _),
98 }) => sig.header.constness == Constness::Const,
103 /// Returns `true` if this `span` was expanded by any macro.
105 pub fn in_macro(span: Span) -> bool {
106 if span.from_expansion() {
107 if let ExpnKind::Desugaring(..) = span.ctxt().outer_expn_data().kind {
116 // If the snippet is empty, it's an attribute that was inserted during macro
117 // expansion and we want to ignore those, because they could come from external
118 // sources that the user has no control over.
119 // For some reason these attributes don't have any expansion info on them, so
120 // we have to check it this way until there is a better way.
121 pub fn is_present_in_source<T: LintContext>(cx: &T, span: Span) -> bool {
122 if let Some(snippet) = snippet_opt(cx, span) {
123 if snippet.is_empty() {
130 /// Checks if given pattern is a wildcard (`_`)
131 pub fn is_wild<'tcx>(pat: &impl std::ops::Deref<Target = Pat<'tcx>>) -> bool {
133 PatKind::Wild => true,
138 /// Checks if type is struct, enum or union type with the given def path.
139 pub fn match_type(cx: &LateContext<'_, '_>, ty: Ty<'_>, path: &[&str]) -> bool {
141 ty::Adt(adt, _) => match_def_path(cx, adt.did, path),
146 /// Checks if the type is equal to a diagnostic item
147 pub fn is_type_diagnostic_item(cx: &LateContext<'_, '_>, ty: Ty<'_>, diag_item: Symbol) -> bool {
149 ty::Adt(adt, _) => cx.tcx.is_diagnostic_item(diag_item, adt.did),
154 /// Checks if the method call given in `expr` belongs to the given trait.
155 pub fn match_trait_method(cx: &LateContext<'_, '_>, expr: &Expr<'_>, path: &[&str]) -> bool {
156 let def_id = cx.tables.type_dependent_def_id(expr.hir_id).unwrap();
157 let trt_id = cx.tcx.trait_of_item(def_id);
158 if let Some(trt_id) = trt_id {
159 match_def_path(cx, trt_id, path)
165 /// Checks if an expression references a variable of the given name.
166 pub fn match_var(expr: &Expr<'_>, var: Name) -> bool {
167 if let ExprKind::Path(QPath::Resolved(None, ref path)) = expr.kind {
168 if path.segments.len() == 1 && path.segments[0].ident.name == var {
175 pub fn last_path_segment<'tcx>(path: &QPath<'tcx>) -> &'tcx PathSegment<'tcx> {
177 QPath::Resolved(_, ref path) => path.segments.last().expect("A path must have at least one segment"),
178 QPath::TypeRelative(_, ref seg) => seg,
182 pub fn single_segment_path<'tcx>(path: &QPath<'tcx>) -> Option<&'tcx PathSegment<'tcx>> {
184 QPath::Resolved(_, ref path) if path.segments.len() == 1 => Some(&path.segments[0]),
185 QPath::Resolved(..) => None,
186 QPath::TypeRelative(_, ref seg) => Some(seg),
190 /// Matches a `QPath` against a slice of segment string literals.
192 /// There is also `match_path` if you are dealing with a `rustc_hir::Path` instead of a
193 /// `rustc_hir::QPath`.
197 /// match_qpath(path, &["std", "rt", "begin_unwind"])
199 pub fn match_qpath(path: &QPath<'_>, segments: &[&str]) -> bool {
201 QPath::Resolved(_, ref path) => match_path(path, segments),
202 QPath::TypeRelative(ref ty, ref segment) => match ty.kind {
203 TyKind::Path(ref inner_path) => {
205 && match_qpath(inner_path, &segments[..(segments.len() - 1)])
206 && segment.ident.name.as_str() == segments[segments.len() - 1]
213 /// Matches a `Path` against a slice of segment string literals.
215 /// There is also `match_qpath` if you are dealing with a `rustc_hir::QPath` instead of a
216 /// `rustc_hir::Path`.
221 /// if match_path(&trait_ref.path, &paths::HASH) {
222 /// // This is the `std::hash::Hash` trait.
225 /// if match_path(ty_path, &["rustc", "lint", "Lint"]) {
226 /// // This is a `rustc::lint::Lint`.
229 pub fn match_path(path: &Path<'_>, segments: &[&str]) -> bool {
233 .zip(segments.iter().rev())
234 .all(|(a, b)| a.ident.name.as_str() == *b)
237 /// Matches a `Path` against a slice of segment string literals, e.g.
241 /// match_qpath(path, &["std", "rt", "begin_unwind"])
243 pub fn match_path_ast(path: &ast::Path, segments: &[&str]) -> bool {
247 .zip(segments.iter().rev())
248 .all(|(a, b)| a.ident.name.as_str() == *b)
251 /// Gets the definition associated to a path.
252 pub fn path_to_res(cx: &LateContext<'_, '_>, path: &[&str]) -> Option<def::Res> {
253 let crates = cx.tcx.crates();
256 .find(|&&krate| cx.tcx.crate_name(krate).as_str() == path[0]);
257 if let Some(krate) = krate {
260 index: CRATE_DEF_INDEX,
262 let mut items = cx.tcx.item_children(krate);
263 let mut path_it = path.iter().skip(1).peekable();
266 let segment = match path_it.next() {
267 Some(segment) => segment,
271 let result = SmallVec::<[_; 8]>::new();
272 for item in mem::replace(&mut items, cx.tcx.arena.alloc_slice(&result)).iter() {
273 if item.ident.name.as_str() == *segment {
274 if path_it.peek().is_none() {
275 return Some(item.res);
278 items = cx.tcx.item_children(item.res.def_id());
288 pub fn qpath_res(cx: &LateContext<'_, '_>, qpath: &hir::QPath<'_>, id: hir::HirId) -> Res {
290 hir::QPath::Resolved(_, path) => path.res,
291 hir::QPath::TypeRelative(..) => {
292 if cx.tcx.has_typeck_tables(id.owner_def_id()) {
293 cx.tcx.typeck_tables_of(id.owner_def_id()).qpath_res(qpath, id)
301 /// Convenience function to get the `DefId` of a trait by path.
302 /// It could be a trait or trait alias.
303 pub fn get_trait_def_id(cx: &LateContext<'_, '_>, path: &[&str]) -> Option<DefId> {
304 let res = match path_to_res(cx, path) {
310 Res::Def(DefKind::Trait, trait_id) | Res::Def(DefKind::TraitAlias, trait_id) => Some(trait_id),
311 Res::Err => unreachable!("this trait resolution is impossible: {:?}", &path),
316 /// Checks whether a type implements a trait.
317 /// See also `get_trait_def_id`.
318 pub fn implements_trait<'a, 'tcx>(
319 cx: &LateContext<'a, 'tcx>,
322 ty_params: &[GenericArg<'tcx>],
324 let ty = cx.tcx.erase_regions(&ty);
325 let obligation = predicate_for_trait_def(
328 traits::ObligationCause::dummy(),
336 .enter(|infcx| infcx.predicate_must_hold_modulo_regions(&obligation))
339 /// Gets the `hir::TraitRef` of the trait the given method is implemented for.
341 /// Use this if you want to find the `TraitRef` of the `Add` trait in this example:
344 /// struct Point(isize, isize);
346 /// impl std::ops::Add for Point {
347 /// type Output = Self;
349 /// fn add(self, other: Self) -> Self {
354 pub fn trait_ref_of_method<'tcx>(cx: &LateContext<'_, 'tcx>, hir_id: HirId) -> Option<&'tcx TraitRef<'tcx>> {
355 // Get the implemented trait for the current function
356 let parent_impl = cx.tcx.hir().get_parent_item(hir_id);
358 if parent_impl != hir::CRATE_HIR_ID;
359 if let hir::Node::Item(item) = cx.tcx.hir().get(parent_impl);
360 if let hir::ItemKind::Impl{ of_trait: trait_ref, .. } = &item.kind;
361 then { return trait_ref.as_ref(); }
366 /// Checks whether this type implements `Drop`.
367 pub fn has_drop<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, ty: Ty<'tcx>) -> bool {
368 match ty.ty_adt_def() {
369 Some(def) => def.has_dtor(cx.tcx),
374 /// Returns the method names and argument list of nested method call expressions that make up
375 /// `expr`. method/span lists are sorted with the most recent call first.
376 pub fn method_calls<'tcx>(
377 expr: &'tcx Expr<'tcx>,
379 ) -> (Vec<Symbol>, Vec<&'tcx [Expr<'tcx>]>, Vec<Span>) {
380 let mut method_names = Vec::with_capacity(max_depth);
381 let mut arg_lists = Vec::with_capacity(max_depth);
382 let mut spans = Vec::with_capacity(max_depth);
384 let mut current = expr;
385 for _ in 0..max_depth {
386 if let ExprKind::MethodCall(path, span, args) = ¤t.kind {
387 if args.iter().any(|e| e.span.from_expansion()) {
390 method_names.push(path.ident.name);
391 arg_lists.push(&**args);
399 (method_names, arg_lists, spans)
402 /// Matches an `Expr` against a chain of methods, and return the matched `Expr`s.
404 /// For example, if `expr` represents the `.baz()` in `foo.bar().baz()`,
405 /// `matched_method_chain(expr, &["bar", "baz"])` will return a `Vec`
406 /// containing the `Expr`s for
407 /// `.bar()` and `.baz()`
408 pub fn method_chain_args<'a>(expr: &'a Expr<'_>, methods: &[&str]) -> Option<Vec<&'a [Expr<'a>]>> {
409 let mut current = expr;
410 let mut matched = Vec::with_capacity(methods.len());
411 for method_name in methods.iter().rev() {
412 // method chains are stored last -> first
413 if let ExprKind::MethodCall(ref path, _, ref args) = current.kind {
414 if path.ident.name.as_str() == *method_name {
415 if args.iter().any(|e| e.span.from_expansion()) {
418 matched.push(&**args); // build up `matched` backwards
419 current = &args[0] // go to parent expression
427 // Reverse `matched` so that it is in the same order as `methods`.
432 /// Returns `true` if the provided `def_id` is an entrypoint to a program.
433 pub fn is_entrypoint_fn(cx: &LateContext<'_, '_>, def_id: DefId) -> bool {
435 .entry_fn(LOCAL_CRATE)
436 .map_or(false, |(entry_fn_def_id, _)| def_id == entry_fn_def_id)
439 /// Gets the name of the item the expression is in, if available.
440 pub fn get_item_name(cx: &LateContext<'_, '_>, expr: &Expr<'_>) -> Option<Name> {
441 let parent_id = cx.tcx.hir().get_parent_item(expr.hir_id);
442 match cx.tcx.hir().find(parent_id) {
443 Some(Node::Item(&Item { ref ident, .. })) => Some(ident.name),
444 Some(Node::TraitItem(&TraitItem { ident, .. })) | Some(Node::ImplItem(&ImplItem { ident, .. })) => {
451 /// Gets the name of a `Pat`, if any.
452 pub fn get_pat_name(pat: &Pat<'_>) -> Option<Name> {
454 PatKind::Binding(.., ref spname, _) => Some(spname.name),
455 PatKind::Path(ref qpath) => single_segment_path(qpath).map(|ps| ps.ident.name),
456 PatKind::Box(ref p) | PatKind::Ref(ref p, _) => get_pat_name(&*p),
461 struct ContainsName {
466 impl<'tcx> Visitor<'tcx> for ContainsName {
467 type Map = Map<'tcx>;
469 fn visit_name(&mut self, _: Span, name: Name) {
470 if self.name == name {
474 fn nested_visit_map(&mut self) -> NestedVisitorMap<'_, Self::Map> {
475 NestedVisitorMap::None
479 /// Checks if an `Expr` contains a certain name.
480 pub fn contains_name(name: Name, expr: &Expr<'_>) -> bool {
481 let mut cn = ContainsName { name, result: false };
486 /// Converts a span to a code snippet if available, otherwise use default.
488 /// This is useful if you want to provide suggestions for your lint or more generally, if you want
489 /// to convert a given `Span` to a `str`.
493 /// snippet(cx, expr.span, "..")
495 pub fn snippet<'a, T: LintContext>(cx: &T, span: Span, default: &'a str) -> Cow<'a, str> {
496 snippet_opt(cx, span).map_or_else(|| Cow::Borrowed(default), From::from)
499 /// Same as `snippet`, but it adapts the applicability level by following rules:
501 /// - Applicability level `Unspecified` will never be changed.
502 /// - If the span is inside a macro, change the applicability level to `MaybeIncorrect`.
503 /// - If the default value is used and the applicability level is `MachineApplicable`, change it to
504 /// `HasPlaceholders`
505 pub fn snippet_with_applicability<'a, T: LintContext>(
509 applicability: &mut Applicability,
511 if *applicability != Applicability::Unspecified && span.from_expansion() {
512 *applicability = Applicability::MaybeIncorrect;
514 snippet_opt(cx, span).map_or_else(
516 if *applicability == Applicability::MachineApplicable {
517 *applicability = Applicability::HasPlaceholders;
519 Cow::Borrowed(default)
525 /// Same as `snippet`, but should only be used when it's clear that the input span is
526 /// not a macro argument.
527 pub fn snippet_with_macro_callsite<'a, T: LintContext>(cx: &T, span: Span, default: &'a str) -> Cow<'a, str> {
528 snippet(cx, span.source_callsite(), default)
531 /// Converts a span to a code snippet. Returns `None` if not available.
532 pub fn snippet_opt<T: LintContext>(cx: &T, span: Span) -> Option<String> {
533 cx.sess().source_map().span_to_snippet(span).ok()
536 /// Converts a span (from a block) to a code snippet if available, otherwise use
538 /// This trims the code of indentation, except for the first line. Use it for
539 /// blocks or block-like
540 /// things which need to be printed as such.
544 /// snippet_block(cx, expr.span, "..")
546 pub fn snippet_block<'a, T: LintContext>(cx: &T, span: Span, default: &'a str) -> Cow<'a, str> {
547 let snip = snippet(cx, span, default);
548 trim_multiline(snip, true)
551 /// Same as `snippet_block`, but adapts the applicability level by the rules of
552 /// `snippet_with_applicabiliy`.
553 pub fn snippet_block_with_applicability<'a, T: LintContext>(
557 applicability: &mut Applicability,
559 let snip = snippet_with_applicability(cx, span, default, applicability);
560 trim_multiline(snip, true)
563 /// Returns a new Span that covers the full last line of the given Span
564 pub fn last_line_of_span<T: LintContext>(cx: &T, span: Span) -> Span {
565 let source_map_and_line = cx.sess().source_map().lookup_line(span.lo()).unwrap();
566 let line_no = source_map_and_line.line;
567 let line_start = &source_map_and_line.sf.lines[line_no];
568 let span = Span::new(*line_start, span.hi(), span.ctxt());
570 if let Some(snip) = snippet_opt(cx, span);
571 if let Some(first_ch_pos) = snip.find(|c: char| !c.is_whitespace());
573 span.with_lo(span.lo() + BytePos::from_usize(first_ch_pos))
580 /// Like `snippet_block`, but add braces if the expr is not an `ExprKind::Block`.
581 /// Also takes an `Option<String>` which can be put inside the braces.
582 pub fn expr_block<'a, T: LintContext>(
585 option: Option<String>,
588 let code = snippet_block(cx, expr.span, default);
589 let string = option.unwrap_or_default();
590 if expr.span.from_expansion() {
591 Cow::Owned(format!("{{ {} }}", snippet_with_macro_callsite(cx, expr.span, default)))
592 } else if let ExprKind::Block(_, _) = expr.kind {
593 Cow::Owned(format!("{}{}", code, string))
594 } else if string.is_empty() {
595 Cow::Owned(format!("{{ {} }}", code))
597 Cow::Owned(format!("{{\n{};\n{}\n}}", code, string))
601 /// Trim indentation from a multiline string with possibility of ignoring the
603 pub fn trim_multiline(s: Cow<'_, str>, ignore_first: bool) -> Cow<'_, str> {
604 let s_space = trim_multiline_inner(s, ignore_first, ' ');
605 let s_tab = trim_multiline_inner(s_space, ignore_first, '\t');
606 trim_multiline_inner(s_tab, ignore_first, ' ')
609 fn trim_multiline_inner(s: Cow<'_, str>, ignore_first: bool, ch: char) -> Cow<'_, str> {
612 .skip(ignore_first as usize)
617 // ignore empty lines
618 Some(l.char_indices().find(|&(_, x)| x != ch).unwrap_or((l.len(), ch)).0)
628 if (ignore_first && i == 0) || l.is_empty() {
642 /// Gets the parent expression, if any –- this is useful to constrain a lint.
643 pub fn get_parent_expr<'c>(cx: &'c LateContext<'_, '_>, e: &Expr<'_>) -> Option<&'c Expr<'c>> {
644 let map = &cx.tcx.hir();
645 let hir_id = e.hir_id;
646 let parent_id = map.get_parent_node(hir_id);
647 if hir_id == parent_id {
650 map.find(parent_id).and_then(|node| {
651 if let Node::Expr(parent) = node {
659 pub fn get_enclosing_block<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, hir_id: HirId) -> Option<&'tcx Block<'tcx>> {
660 let map = &cx.tcx.hir();
661 let enclosing_node = map
662 .get_enclosing_scope(hir_id)
663 .and_then(|enclosing_id| map.find(enclosing_id));
664 if let Some(node) = enclosing_node {
666 Node::Block(block) => Some(block),
668 kind: ItemKind::Fn(_, _, eid),
671 | Node::ImplItem(&ImplItem {
672 kind: ImplItemKind::Method(_, eid),
674 }) => match cx.tcx.hir().body(eid).value.kind {
675 ExprKind::Block(ref block, _) => Some(block),
685 /// Returns the base type for HIR references and pointers.
686 pub fn walk_ptrs_hir_ty<'tcx>(ty: &'tcx hir::Ty<'tcx>) -> &'tcx hir::Ty<'tcx> {
688 TyKind::Ptr(ref mut_ty) | TyKind::Rptr(_, ref mut_ty) => walk_ptrs_hir_ty(&mut_ty.ty),
693 /// Returns the base type for references and raw pointers.
694 pub fn walk_ptrs_ty(ty: Ty<'_>) -> Ty<'_> {
696 ty::Ref(_, ty, _) => walk_ptrs_ty(ty),
701 /// Returns the base type for references and raw pointers, and count reference
703 pub fn walk_ptrs_ty_depth(ty: Ty<'_>) -> (Ty<'_>, usize) {
704 fn inner(ty: Ty<'_>, depth: usize) -> (Ty<'_>, usize) {
706 ty::Ref(_, ty, _) => inner(ty, depth + 1),
713 /// Checks whether the given expression is a constant integer of the given value.
714 /// unlike `is_integer_literal`, this version does const folding
715 pub fn is_integer_const(cx: &LateContext<'_, '_>, e: &Expr<'_>, value: u128) -> bool {
716 if is_integer_literal(e, value) {
719 let map = cx.tcx.hir();
720 let parent_item = map.get_parent_item(e.hir_id);
721 if let Some((Constant::Int(v), _)) = map
722 .maybe_body_owned_by(parent_item)
723 .and_then(|body_id| constant(cx, cx.tcx.body_tables(body_id), e))
731 /// Checks whether the given expression is a constant literal of the given value.
732 pub fn is_integer_literal(expr: &Expr<'_>, value: u128) -> bool {
733 // FIXME: use constant folding
734 if let ExprKind::Lit(ref spanned) = expr.kind {
735 if let LitKind::Int(v, _) = spanned.node {
742 /// Returns `true` if the given `Expr` has been coerced before.
744 /// Examples of coercions can be found in the Nomicon at
745 /// <https://doc.rust-lang.org/nomicon/coercions.html>.
747 /// See `rustc::ty::adjustment::Adjustment` and `rustc_typeck::check::coercion` for more
748 /// information on adjustments and coercions.
749 pub fn is_adjusted(cx: &LateContext<'_, '_>, e: &Expr<'_>) -> bool {
750 cx.tables.adjustments().get(e.hir_id).is_some()
753 /// Returns the pre-expansion span if is this comes from an expansion of the
755 /// See also `is_direct_expn_of`.
757 pub fn is_expn_of(mut span: Span, name: &str) -> Option<Span> {
759 if span.from_expansion() {
760 let data = span.ctxt().outer_expn_data();
761 let mac_name = data.kind.descr();
762 let new_span = data.call_site;
764 if mac_name.as_str() == name {
765 return Some(new_span);
775 /// Returns the pre-expansion span if the span directly comes from an expansion
776 /// of the macro `name`.
777 /// The difference with `is_expn_of` is that in
781 /// `42` is considered expanded from `foo!` and `bar!` by `is_expn_of` but only
783 /// `is_direct_expn_of`.
785 pub fn is_direct_expn_of(span: Span, name: &str) -> Option<Span> {
786 if span.from_expansion() {
787 let data = span.ctxt().outer_expn_data();
788 let mac_name = data.kind.descr();
789 let new_span = data.call_site;
791 if mac_name.as_str() == name {
801 /// Convenience function to get the return type of a function.
802 pub fn return_ty<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, fn_item: hir::HirId) -> Ty<'tcx> {
803 let fn_def_id = cx.tcx.hir().local_def_id(fn_item);
804 let ret_ty = cx.tcx.fn_sig(fn_def_id).output();
805 cx.tcx.erase_late_bound_regions(&ret_ty)
808 /// Checks if two types are the same.
810 /// This discards any lifetime annotations, too.
812 // FIXME: this works correctly for lifetimes bounds (`for <'a> Foo<'a>` ==
813 // `for <'b> Foo<'b>`, but not for type parameters).
814 pub fn same_tys<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, a: Ty<'tcx>, b: Ty<'tcx>) -> bool {
815 let a = cx.tcx.erase_late_bound_regions(&Binder::bind(a));
816 let b = cx.tcx.erase_late_bound_regions(&Binder::bind(b));
819 .enter(|infcx| infcx.can_eq(cx.param_env, a, b).is_ok())
822 /// Returns `true` if the given type is an `unsafe` function.
823 pub fn type_is_unsafe_function<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, ty: Ty<'tcx>) -> bool {
825 ty::FnDef(..) | ty::FnPtr(_) => ty.fn_sig(cx.tcx).unsafety() == Unsafety::Unsafe,
830 pub fn is_copy<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, ty: Ty<'tcx>) -> bool {
831 ty.is_copy_modulo_regions(cx.tcx, cx.param_env, DUMMY_SP)
834 /// Checks if an expression is constructing a tuple-like enum variant or struct
835 pub fn is_ctor_or_promotable_const_function(cx: &LateContext<'_, '_>, expr: &Expr<'_>) -> bool {
836 if let ExprKind::Call(ref fun, _) = expr.kind {
837 if let ExprKind::Path(ref qp) = fun.kind {
838 let res = cx.tables.qpath_res(qp, fun.hir_id);
840 def::Res::Def(DefKind::Variant, ..) | Res::Def(DefKind::Ctor(..), _) => true,
841 def::Res::Def(_, def_id) => cx.tcx.is_promotable_const_fn(def_id),
849 /// Returns `true` if a pattern is refutable.
850 pub fn is_refutable(cx: &LateContext<'_, '_>, pat: &Pat<'_>) -> bool {
851 fn is_enum_variant(cx: &LateContext<'_, '_>, qpath: &QPath<'_>, id: HirId) -> bool {
853 cx.tables.qpath_res(qpath, id),
854 def::Res::Def(DefKind::Variant, ..) | Res::Def(DefKind::Ctor(def::CtorOf::Variant, _), _)
858 fn are_refutable<'a, I: Iterator<Item = &'a Pat<'a>>>(cx: &LateContext<'_, '_>, mut i: I) -> bool {
859 i.any(|pat| is_refutable(cx, pat))
863 PatKind::Binding(..) | PatKind::Wild => false,
864 PatKind::Box(ref pat) | PatKind::Ref(ref pat, _) => is_refutable(cx, pat),
865 PatKind::Lit(..) | PatKind::Range(..) => true,
866 PatKind::Path(ref qpath) => is_enum_variant(cx, qpath, pat.hir_id),
867 PatKind::Or(ref pats) | PatKind::Tuple(ref pats, _) => are_refutable(cx, pats.iter().map(|pat| &**pat)),
868 PatKind::Struct(ref qpath, ref fields, _) => {
869 if is_enum_variant(cx, qpath, pat.hir_id) {
872 are_refutable(cx, fields.iter().map(|field| &*field.pat))
875 PatKind::TupleStruct(ref qpath, ref pats, _) => {
876 if is_enum_variant(cx, qpath, pat.hir_id) {
879 are_refutable(cx, pats.iter().map(|pat| &**pat))
882 PatKind::Slice(ref head, ref middle, ref tail) => {
883 are_refutable(cx, head.iter().chain(middle).chain(tail.iter()).map(|pat| &**pat))
888 /// Checks for the `#[automatically_derived]` attribute all `#[derive]`d
889 /// implementations have.
890 pub fn is_automatically_derived(attrs: &[ast::Attribute]) -> bool {
891 attr::contains_name(attrs, sym!(automatically_derived))
894 /// Remove blocks around an expression.
896 /// Ie. `x`, `{ x }` and `{{{{ x }}}}` all give `x`. `{ x; y }` and `{}` return
898 pub fn remove_blocks<'tcx>(mut expr: &'tcx Expr<'tcx>) -> &'tcx Expr<'tcx> {
899 while let ExprKind::Block(ref block, ..) = expr.kind {
900 match (block.stmts.is_empty(), block.expr.as_ref()) {
901 (true, Some(e)) => expr = e,
908 pub fn is_self(slf: &Param<'_>) -> bool {
909 if let PatKind::Binding(.., name, _) = slf.pat.kind {
910 name.name == kw::SelfLower
916 pub fn is_self_ty(slf: &hir::Ty<'_>) -> bool {
918 if let TyKind::Path(ref qp) = slf.kind;
919 if let QPath::Resolved(None, ref path) = *qp;
920 if let Res::SelfTy(..) = path.res;
928 pub fn iter_input_pats<'tcx>(decl: &FnDecl<'_>, body: &'tcx Body<'_>) -> impl Iterator<Item = &'tcx Param<'tcx>> {
929 (0..decl.inputs.len()).map(move |i| &body.params[i])
932 /// Checks if a given expression is a match expression expanded from the `?`
933 /// operator or the `try` macro.
934 pub fn is_try<'tcx>(expr: &'tcx Expr<'tcx>) -> Option<&'tcx Expr<'tcx>> {
935 fn is_ok(arm: &Arm<'_>) -> bool {
937 if let PatKind::TupleStruct(ref path, ref pat, None) = arm.pat.kind;
938 if match_qpath(path, &paths::RESULT_OK[1..]);
939 if let PatKind::Binding(_, hir_id, _, None) = pat[0].kind;
940 if let ExprKind::Path(QPath::Resolved(None, ref path)) = arm.body.kind;
941 if let Res::Local(lid) = path.res;
950 fn is_err(arm: &Arm<'_>) -> bool {
951 if let PatKind::TupleStruct(ref path, _, _) = arm.pat.kind {
952 match_qpath(path, &paths::RESULT_ERR[1..])
958 if let ExprKind::Match(_, ref arms, ref source) = expr.kind {
959 // desugared from a `?` operator
960 if let MatchSource::TryDesugar = *source {
966 if arms[0].guard.is_none();
967 if arms[1].guard.is_none();
968 if (is_ok(&arms[0]) && is_err(&arms[1])) ||
969 (is_ok(&arms[1]) && is_err(&arms[0]));
979 /// Returns `true` if the lint is allowed in the current context
981 /// Useful for skipping long running code when it's unnecessary
982 pub fn is_allowed(cx: &LateContext<'_, '_>, lint: &'static Lint, id: HirId) -> bool {
983 cx.tcx.lint_level_at_node(lint, id).0 == Level::Allow
986 pub fn get_arg_name(pat: &Pat<'_>) -> Option<ast::Name> {
988 PatKind::Binding(.., ident, None) => Some(ident.name),
989 PatKind::Ref(ref subpat, _) => get_arg_name(subpat),
994 pub fn int_bits(tcx: TyCtxt<'_>, ity: ast::IntTy) -> u64 {
995 layout::Integer::from_attr(&tcx, attr::IntType::SignedInt(ity))
1000 #[allow(clippy::cast_possible_wrap)]
1001 /// Turn a constant int byte representation into an i128
1002 pub fn sext(tcx: TyCtxt<'_>, u: u128, ity: ast::IntTy) -> i128 {
1003 let amt = 128 - int_bits(tcx, ity);
1004 ((u as i128) << amt) >> amt
1007 #[allow(clippy::cast_sign_loss)]
1008 /// clip unused bytes
1009 pub fn unsext(tcx: TyCtxt<'_>, u: i128, ity: ast::IntTy) -> u128 {
1010 let amt = 128 - int_bits(tcx, ity);
1011 ((u as u128) << amt) >> amt
1014 /// clip unused bytes
1015 pub fn clip(tcx: TyCtxt<'_>, u: u128, ity: ast::UintTy) -> u128 {
1016 let bits = layout::Integer::from_attr(&tcx, attr::IntType::UnsignedInt(ity))
1019 let amt = 128 - bits;
1023 /// Removes block comments from the given `Vec` of lines.
1028 /// without_block_comments(vec!["/*", "foo", "*/"]);
1031 /// without_block_comments(vec!["bar", "/*", "foo", "*/"]);
1032 /// // => vec!["bar"]
1034 pub fn without_block_comments(lines: Vec<&str>) -> Vec<&str> {
1035 let mut without = vec![];
1037 let mut nest_level = 0;
1040 if line.contains("/*") {
1043 } else if line.contains("*/") {
1048 if nest_level == 0 {
1056 pub fn any_parent_is_automatically_derived(tcx: TyCtxt<'_>, node: HirId) -> bool {
1057 let map = &tcx.hir();
1058 let mut prev_enclosing_node = None;
1059 let mut enclosing_node = node;
1060 while Some(enclosing_node) != prev_enclosing_node {
1061 if is_automatically_derived(map.attrs(enclosing_node)) {
1064 prev_enclosing_node = Some(enclosing_node);
1065 enclosing_node = map.get_parent_item(enclosing_node);
1070 /// Returns true if ty has `iter` or `iter_mut` methods
1071 pub fn has_iter_method(cx: &LateContext<'_, '_>, probably_ref_ty: Ty<'_>) -> Option<&'static str> {
1072 // FIXME: instead of this hard-coded list, we should check if `<adt>::iter`
1073 // exists and has the desired signature. Unfortunately FnCtxt is not exported
1074 // so we can't use its `lookup_method` method.
1075 let into_iter_collections: [&[&str]; 13] = [
1082 &paths::LINKED_LIST,
1083 &paths::BINARY_HEAP,
1091 let ty_to_check = match probably_ref_ty.kind {
1092 ty::Ref(_, ty_to_check, _) => ty_to_check,
1093 _ => probably_ref_ty,
1096 let def_id = match ty_to_check.kind {
1097 ty::Array(..) => return Some("array"),
1098 ty::Slice(..) => return Some("slice"),
1099 ty::Adt(adt, _) => adt.did,
1103 for path in &into_iter_collections {
1104 if match_def_path(cx, def_id, path) {
1105 return Some(*path.last().unwrap());
1111 /// Matches a function call with the given path and returns the arguments.
1116 /// if let Some(args) = match_function_call(cx, begin_panic_call, &paths::BEGIN_PANIC);
1118 pub fn match_function_call<'a, 'tcx>(
1119 cx: &LateContext<'a, 'tcx>,
1120 expr: &'tcx Expr<'_>,
1122 ) -> Option<&'tcx [Expr<'tcx>]> {
1124 if let ExprKind::Call(ref fun, ref args) = expr.kind;
1125 if let ExprKind::Path(ref qpath) = fun.kind;
1126 if let Some(fun_def_id) = cx.tables.qpath_res(qpath, fun.hir_id).opt_def_id();
1127 if match_def_path(cx, fun_def_id, path);
1135 /// Checks if `Ty` is normalizable. This function is useful
1136 /// to avoid crashes on `layout_of`.
1137 pub fn is_normalizable<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, param_env: ty::ParamEnv<'tcx>, ty: Ty<'tcx>) -> bool {
1138 cx.tcx.infer_ctxt().enter(|infcx| {
1139 let cause = rustc::traits::ObligationCause::dummy();
1140 infcx.at(&cause, param_env).normalize(&ty).is_ok()
1146 use super::{trim_multiline, without_block_comments};
1149 fn test_trim_multiline_single_line() {
1150 assert_eq!("", trim_multiline("".into(), false));
1151 assert_eq!("...", trim_multiline("...".into(), false));
1152 assert_eq!("...", trim_multiline(" ...".into(), false));
1153 assert_eq!("...", trim_multiline("\t...".into(), false));
1154 assert_eq!("...", trim_multiline("\t\t...".into(), false));
1159 fn test_trim_multiline_block() {
1165 }", trim_multiline(" if x {
1175 }", trim_multiline(" if x {
1184 fn test_trim_multiline_empty_line() {
1191 }", trim_multiline(" if x {
1200 fn test_without_block_comments_lines_without_block_comments() {
1201 let result = without_block_comments(vec!["/*", "", "*/"]);
1202 println!("result: {:?}", result);
1203 assert!(result.is_empty());
1205 let result = without_block_comments(vec!["", "/*", "", "*/", "#[crate_type = \"lib\"]", "/*", "", "*/", ""]);
1206 assert_eq!(result, vec!["", "#[crate_type = \"lib\"]", ""]);
1208 let result = without_block_comments(vec!["/* rust", "", "*/"]);
1209 assert!(result.is_empty());
1211 let result = without_block_comments(vec!["/* one-line comment */"]);
1212 assert!(result.is_empty());
1214 let result = without_block_comments(vec!["/* nested", "/* multi-line", "comment", "*/", "test", "*/"]);
1215 assert!(result.is_empty());
1217 let result = without_block_comments(vec!["/* nested /* inline /* comment */ test */ */"]);
1218 assert!(result.is_empty());
1220 let result = without_block_comments(vec!["foo", "bar", "baz"]);
1221 assert_eq!(result, vec!["foo", "bar", "baz"]);
1225 pub fn match_def_path<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, did: DefId, syms: &[&str]) -> bool {
1226 let path = cx.get_def_path(did);
1227 path.len() == syms.len() && path.into_iter().zip(syms.iter()).all(|(a, &b)| a.as_str() == b)
1230 /// Returns the list of condition expressions and the list of blocks in a
1231 /// sequence of `if/else`.
1232 /// E.g., this returns `([a, b], [c, d, e])` for the expression
1233 /// `if a { c } else if b { d } else { e }`.
1234 pub fn if_sequence<'tcx>(
1235 mut expr: &'tcx Expr<'tcx>,
1236 ) -> (SmallVec<[&'tcx Expr<'tcx>; 1]>, SmallVec<[&'tcx Block<'tcx>; 1]>) {
1237 let mut conds = SmallVec::new();
1238 let mut blocks: SmallVec<[&Block<'_>; 1]> = SmallVec::new();
1240 while let Some((ref cond, ref then_expr, ref else_expr)) = higher::if_block(&expr) {
1241 conds.push(&**cond);
1242 if let ExprKind::Block(ref block, _) = then_expr.kind {
1245 panic!("ExprKind::If node is not an ExprKind::Block");
1248 if let Some(ref else_expr) = *else_expr {
1255 // final `else {..}`
1256 if !blocks.is_empty() {
1257 if let ExprKind::Block(ref block, _) = expr.kind {
1258 blocks.push(&**block);
1265 pub fn parent_node_is_if_expr<'a, 'b>(expr: &Expr<'_>, cx: &LateContext<'a, 'b>) -> bool {
1266 let map = cx.tcx.hir();
1267 let parent_id = map.get_parent_node(expr.hir_id);
1268 let parent_node = map.get(parent_id);
1271 Node::Expr(e) => higher::if_block(&e).is_some(),
1272 Node::Arm(e) => higher::if_block(&e.body).is_some(),
1277 // Finds the attribute with the given name, if any
1278 pub fn attr_by_name<'a>(attrs: &'a [Attribute], name: &'_ str) -> Option<&'a Attribute> {
1281 .find(|attr| attr.ident().map_or(false, |ident| ident.as_str() == name))
1284 // Finds the `#[must_use]` attribute, if any
1285 pub fn must_use_attr(attrs: &[Attribute]) -> Option<&Attribute> {
1286 attr_by_name(attrs, "must_use")
1289 // Returns whether the type has #[must_use] attribute
1290 pub fn is_must_use_ty<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, ty: Ty<'tcx>) -> bool {
1293 Adt(ref adt, _) => must_use_attr(&cx.tcx.get_attrs(adt.did)).is_some(),
1294 Foreign(ref did) => must_use_attr(&cx.tcx.get_attrs(*did)).is_some(),
1295 Slice(ref ty) | Array(ref ty, _) | RawPtr(ty::TypeAndMut { ref ty, .. }) | Ref(_, ref ty, _) => {
1296 // for the Array case we don't need to care for the len == 0 case
1297 // because we don't want to lint functions returning empty arrays
1298 is_must_use_ty(cx, *ty)
1300 Tuple(ref substs) => substs.types().any(|ty| is_must_use_ty(cx, ty)),
1301 Opaque(ref def_id, _) => {
1302 for (predicate, _) in cx.tcx.predicates_of(*def_id).predicates {
1303 if let ty::Predicate::Trait(ref poly_trait_predicate) = predicate {
1304 if must_use_attr(&cx.tcx.get_attrs(poly_trait_predicate.skip_binder().trait_ref.def_id)).is_some() {
1311 Dynamic(binder, _) => {
1312 for predicate in binder.skip_binder().iter() {
1313 if let ty::ExistentialPredicate::Trait(ref trait_ref) = predicate {
1314 if must_use_attr(&cx.tcx.get_attrs(trait_ref.def_id)).is_some() {
1325 // check if expr is calling method or function with #[must_use] attribyte
1326 pub fn is_must_use_func_call(cx: &LateContext<'_, '_>, expr: &Expr<'_>) -> bool {
1327 let did = match expr.kind {
1328 ExprKind::Call(ref path, _) => if_chain! {
1329 if let ExprKind::Path(ref qpath) = path.kind;
1330 if let def::Res::Def(_, did) = cx.tables.qpath_res(qpath, path.hir_id);
1337 ExprKind::MethodCall(_, _, _) => cx.tables.type_dependent_def_id(expr.hir_id),
1341 if let Some(did) = did {
1342 must_use_attr(&cx.tcx.get_attrs(did)).is_some()