4 #[allow(clippy::module_name_repetitions)]
16 pub mod internal_lints;
17 pub mod numeric_literal;
22 pub use self::attrs::*;
23 pub use self::diagnostics::*;
24 pub use self::hir_utils::{both, over, SpanlessEq, SpanlessHash};
29 use if_chain::if_chain;
30 use rustc_ast::ast::{self, Attribute, LitKind};
31 use rustc_attr as attr;
32 use rustc_errors::Applicability;
34 use rustc_hir::def::{DefKind, Res};
35 use rustc_hir::def_id::{DefId, CRATE_DEF_INDEX, LOCAL_CRATE};
36 use rustc_hir::intravisit::{NestedVisitorMap, Visitor};
39 def, Arm, Block, Body, Constness, Crate, Expr, ExprKind, FnDecl, HirId, ImplItem, ImplItemKind, Item, ItemKind,
40 MatchSource, Param, Pat, PatKind, Path, PathSegment, QPath, TraitItem, TraitItemKind, TraitRef, TyKind, Unsafety,
42 use rustc_infer::infer::TyCtxtInferExt;
43 use rustc_lint::{LateContext, Level, Lint, LintContext};
44 use rustc_middle::hir::map::Map;
45 use rustc_middle::ty::{self, layout::IntegerExt, subst::GenericArg, Ty, TyCtxt, TypeFoldable};
46 use rustc_span::hygiene::{ExpnKind, MacroKind};
47 use rustc_span::source_map::original_sp;
48 use rustc_span::symbol::{self, kw, Symbol};
49 use rustc_span::{BytePos, Pos, Span, DUMMY_SP};
50 use rustc_target::abi::Integer;
51 use rustc_trait_selection::traits::query::normalize::AtExt;
52 use smallvec::SmallVec;
54 use crate::consts::{constant, Constant};
55 use crate::reexport::Name;
57 /// Returns `true` if the two spans come from differing expansions (i.e., one is
58 /// from a macro and one isn't).
60 pub fn differing_macro_contexts(lhs: Span, rhs: Span) -> bool {
61 rhs.ctxt() != lhs.ctxt()
64 /// Returns `true` if the given `NodeId` is inside a constant context
69 /// if in_constant(cx, expr.hir_id) {
73 pub fn in_constant(cx: &LateContext<'_>, id: HirId) -> bool {
74 let parent_id = cx.tcx.hir().get_parent_item(id);
75 match cx.tcx.hir().get(parent_id) {
77 kind: ItemKind::Const(..) | ItemKind::Static(..),
80 | Node::TraitItem(&TraitItem {
81 kind: TraitItemKind::Const(..),
84 | Node::ImplItem(&ImplItem {
85 kind: ImplItemKind::Const(..),
88 | Node::AnonConst(_) => true,
90 kind: ItemKind::Fn(ref sig, ..),
93 | Node::ImplItem(&ImplItem {
94 kind: ImplItemKind::Fn(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 !matches!(span.ctxt().outer_expn_data().kind, ExpnKind::Desugaring(..))
110 // If the snippet is empty, it's an attribute that was inserted during macro
111 // expansion and we want to ignore those, because they could come from external
112 // sources that the user has no control over.
113 // For some reason these attributes don't have any expansion info on them, so
114 // we have to check it this way until there is a better way.
115 pub fn is_present_in_source<T: LintContext>(cx: &T, span: Span) -> bool {
116 if let Some(snippet) = snippet_opt(cx, span) {
117 if snippet.is_empty() {
124 /// Checks if given pattern is a wildcard (`_`)
125 pub fn is_wild<'tcx>(pat: &impl std::ops::Deref<Target = Pat<'tcx>>) -> bool {
126 matches!(pat.kind, PatKind::Wild)
129 /// Checks if type is struct, enum or union type with the given def path.
130 pub fn match_type(cx: &LateContext<'_>, ty: Ty<'_>, path: &[&str]) -> bool {
132 ty::Adt(adt, _) => match_def_path(cx, adt.did, path),
137 /// Checks if the type is equal to a diagnostic item
138 pub fn is_type_diagnostic_item(cx: &LateContext<'_>, ty: Ty<'_>, diag_item: Symbol) -> bool {
140 ty::Adt(adt, _) => cx.tcx.is_diagnostic_item(diag_item, adt.did),
145 /// Checks if the method call given in `expr` belongs to the given trait.
146 pub fn match_trait_method(cx: &LateContext<'_>, expr: &Expr<'_>, path: &[&str]) -> bool {
147 let def_id = cx.tables().type_dependent_def_id(expr.hir_id).unwrap();
148 let trt_id = cx.tcx.trait_of_item(def_id);
149 trt_id.map_or(false, |trt_id| match_def_path(cx, trt_id, path))
152 /// Checks if an expression references a variable of the given name.
153 pub fn match_var(expr: &Expr<'_>, var: Name) -> bool {
154 if let ExprKind::Path(QPath::Resolved(None, ref path)) = expr.kind {
155 if let [p] = path.segments {
156 return p.ident.name == var;
162 pub fn last_path_segment<'tcx>(path: &QPath<'tcx>) -> &'tcx PathSegment<'tcx> {
164 QPath::Resolved(_, ref path) => path.segments.last().expect("A path must have at least one segment"),
165 QPath::TypeRelative(_, ref seg) => seg,
169 pub fn single_segment_path<'tcx>(path: &QPath<'tcx>) -> Option<&'tcx PathSegment<'tcx>> {
171 QPath::Resolved(_, ref path) => path.segments.get(0),
172 QPath::TypeRelative(_, ref seg) => Some(seg),
176 /// Matches a `QPath` against a slice of segment string literals.
178 /// There is also `match_path` if you are dealing with a `rustc_hir::Path` instead of a
179 /// `rustc_hir::QPath`.
183 /// match_qpath(path, &["std", "rt", "begin_unwind"])
185 pub fn match_qpath(path: &QPath<'_>, segments: &[&str]) -> bool {
187 QPath::Resolved(_, ref path) => match_path(path, segments),
188 QPath::TypeRelative(ref ty, ref segment) => match ty.kind {
189 TyKind::Path(ref inner_path) => {
190 if let [prefix @ .., end] = segments {
191 if match_qpath(inner_path, prefix) {
192 return segment.ident.name.as_str() == *end;
202 /// Matches a `Path` against a slice of segment string literals.
204 /// There is also `match_qpath` if you are dealing with a `rustc_hir::QPath` instead of a
205 /// `rustc_hir::Path`.
210 /// if match_path(&trait_ref.path, &paths::HASH) {
211 /// // This is the `std::hash::Hash` trait.
214 /// if match_path(ty_path, &["rustc", "lint", "Lint"]) {
215 /// // This is a `rustc_middle::lint::Lint`.
218 pub fn match_path(path: &Path<'_>, segments: &[&str]) -> bool {
222 .zip(segments.iter().rev())
223 .all(|(a, b)| a.ident.name.as_str() == *b)
226 /// Matches a `Path` against a slice of segment string literals, e.g.
230 /// match_path_ast(path, &["std", "rt", "begin_unwind"])
232 pub fn match_path_ast(path: &ast::Path, segments: &[&str]) -> bool {
236 .zip(segments.iter().rev())
237 .all(|(a, b)| a.ident.name.as_str() == *b)
240 /// Gets the definition associated to a path.
241 pub fn path_to_res(cx: &LateContext<'_>, path: &[&str]) -> Option<def::Res> {
242 let crates = cx.tcx.crates();
245 .find(|&&krate| cx.tcx.crate_name(krate).as_str() == path[0]);
246 if let Some(krate) = krate {
249 index: CRATE_DEF_INDEX,
251 let mut items = cx.tcx.item_children(krate);
252 let mut path_it = path.iter().skip(1).peekable();
255 let segment = match path_it.next() {
256 Some(segment) => segment,
260 let result = SmallVec::<[_; 8]>::new();
261 for item in mem::replace(&mut items, cx.tcx.arena.alloc_slice(&result)).iter() {
262 if item.ident.name.as_str() == *segment {
263 if path_it.peek().is_none() {
264 return Some(item.res);
267 items = cx.tcx.item_children(item.res.def_id());
277 pub fn qpath_res(cx: &LateContext<'_>, qpath: &hir::QPath<'_>, id: hir::HirId) -> Res {
279 hir::QPath::Resolved(_, path) => path.res,
280 hir::QPath::TypeRelative(..) => {
281 if cx.tcx.has_typeck_tables(id.owner.to_def_id()) {
283 .typeck_tables_of(id.owner.to_def_id().expect_local())
284 .qpath_res(qpath, id)
292 /// Convenience function to get the `DefId` of a trait by path.
293 /// It could be a trait or trait alias.
294 pub fn get_trait_def_id(cx: &LateContext<'_>, path: &[&str]) -> Option<DefId> {
295 let res = match path_to_res(cx, path) {
301 Res::Def(DefKind::Trait | DefKind::TraitAlias, trait_id) => Some(trait_id),
302 Res::Err => unreachable!("this trait resolution is impossible: {:?}", &path),
307 /// Checks whether a type implements a trait.
308 /// See also `get_trait_def_id`.
309 pub fn implements_trait<'tcx>(
310 cx: &LateContext<'tcx>,
313 ty_params: &[GenericArg<'tcx>],
315 // Do not check on infer_types to avoid panic in evaluate_obligation.
316 if ty.has_infer_types() {
319 let ty = cx.tcx.erase_regions(&ty);
320 let ty_params = cx.tcx.mk_substs(ty_params.iter());
321 cx.tcx.type_implements_trait((trait_id, ty, ty_params, cx.param_env))
324 /// Gets the `hir::TraitRef` of the trait the given method is implemented for.
326 /// Use this if you want to find the `TraitRef` of the `Add` trait in this example:
329 /// struct Point(isize, isize);
331 /// impl std::ops::Add for Point {
332 /// type Output = Self;
334 /// fn add(self, other: Self) -> Self {
339 pub fn trait_ref_of_method<'tcx>(cx: &LateContext<'tcx>, hir_id: HirId) -> Option<&'tcx TraitRef<'tcx>> {
340 // Get the implemented trait for the current function
341 let parent_impl = cx.tcx.hir().get_parent_item(hir_id);
343 if parent_impl != hir::CRATE_HIR_ID;
344 if let hir::Node::Item(item) = cx.tcx.hir().get(parent_impl);
345 if let hir::ItemKind::Impl{ of_trait: trait_ref, .. } = &item.kind;
346 then { return trait_ref.as_ref(); }
351 /// Checks whether this type implements `Drop`.
352 pub fn has_drop<'tcx>(cx: &LateContext<'tcx>, ty: Ty<'tcx>) -> bool {
353 match ty.ty_adt_def() {
354 Some(def) => def.has_dtor(cx.tcx),
359 /// Returns the method names and argument list of nested method call expressions that make up
360 /// `expr`. method/span lists are sorted with the most recent call first.
361 pub fn method_calls<'tcx>(
362 expr: &'tcx Expr<'tcx>,
364 ) -> (Vec<Symbol>, Vec<&'tcx [Expr<'tcx>]>, Vec<Span>) {
365 let mut method_names = Vec::with_capacity(max_depth);
366 let mut arg_lists = Vec::with_capacity(max_depth);
367 let mut spans = Vec::with_capacity(max_depth);
369 let mut current = expr;
370 for _ in 0..max_depth {
371 if let ExprKind::MethodCall(path, span, args, _) = ¤t.kind {
372 if args.iter().any(|e| e.span.from_expansion()) {
375 method_names.push(path.ident.name);
376 arg_lists.push(&**args);
384 (method_names, arg_lists, spans)
387 /// Matches an `Expr` against a chain of methods, and return the matched `Expr`s.
389 /// For example, if `expr` represents the `.baz()` in `foo.bar().baz()`,
390 /// `method_chain_args(expr, &["bar", "baz"])` will return a `Vec`
391 /// containing the `Expr`s for
392 /// `.bar()` and `.baz()`
393 pub fn method_chain_args<'a>(expr: &'a Expr<'_>, methods: &[&str]) -> Option<Vec<&'a [Expr<'a>]>> {
394 let mut current = expr;
395 let mut matched = Vec::with_capacity(methods.len());
396 for method_name in methods.iter().rev() {
397 // method chains are stored last -> first
398 if let ExprKind::MethodCall(ref path, _, ref args, _) = current.kind {
399 if path.ident.name.as_str() == *method_name {
400 if args.iter().any(|e| e.span.from_expansion()) {
403 matched.push(&**args); // build up `matched` backwards
404 current = &args[0] // go to parent expression
412 // Reverse `matched` so that it is in the same order as `methods`.
417 /// Returns `true` if the provided `def_id` is an entrypoint to a program.
418 pub fn is_entrypoint_fn(cx: &LateContext<'_>, def_id: DefId) -> bool {
420 .entry_fn(LOCAL_CRATE)
421 .map_or(false, |(entry_fn_def_id, _)| def_id == entry_fn_def_id.to_def_id())
424 /// Gets the name of the item the expression is in, if available.
425 pub fn get_item_name(cx: &LateContext<'_>, expr: &Expr<'_>) -> Option<Name> {
426 let parent_id = cx.tcx.hir().get_parent_item(expr.hir_id);
427 match cx.tcx.hir().find(parent_id) {
429 Node::Item(Item { ident, .. })
430 | Node::TraitItem(TraitItem { ident, .. })
431 | Node::ImplItem(ImplItem { ident, .. }),
432 ) => Some(ident.name),
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 type Map = Map<'tcx>;
455 fn visit_name(&mut self, _: Span, name: Name) {
456 if self.name == name {
460 fn nested_visit_map(&mut self) -> NestedVisitorMap<Self::Map> {
461 NestedVisitorMap::None
465 /// Checks if an `Expr` contains a certain name.
466 pub fn contains_name(name: Name, expr: &Expr<'_>) -> bool {
467 let mut cn = ContainsName { name, result: false };
472 /// Converts a span to a code snippet if available, otherwise use default.
474 /// This is useful if you want to provide suggestions for your lint or more generally, if you want
475 /// to convert a given `Span` to a `str`.
479 /// snippet(cx, expr.span, "..")
481 pub fn snippet<'a, T: LintContext>(cx: &T, span: Span, default: &'a str) -> Cow<'a, str> {
482 snippet_opt(cx, span).map_or_else(|| Cow::Borrowed(default), From::from)
485 /// Same as `snippet`, but it adapts the applicability level by following rules:
487 /// - Applicability level `Unspecified` will never be changed.
488 /// - If the span is inside a macro, change the applicability level to `MaybeIncorrect`.
489 /// - If the default value is used and the applicability level is `MachineApplicable`, change it to
490 /// `HasPlaceholders`
491 pub fn snippet_with_applicability<'a, T: LintContext>(
495 applicability: &mut Applicability,
497 if *applicability != Applicability::Unspecified && span.from_expansion() {
498 *applicability = Applicability::MaybeIncorrect;
500 snippet_opt(cx, span).map_or_else(
502 if *applicability == Applicability::MachineApplicable {
503 *applicability = Applicability::HasPlaceholders;
505 Cow::Borrowed(default)
511 /// Same as `snippet`, but should only be used when it's clear that the input span is
512 /// not a macro argument.
513 pub fn snippet_with_macro_callsite<'a, T: LintContext>(cx: &T, span: Span, default: &'a str) -> Cow<'a, str> {
514 snippet(cx, span.source_callsite(), default)
517 /// Converts a span to a code snippet. Returns `None` if not available.
518 pub fn snippet_opt<T: LintContext>(cx: &T, span: Span) -> Option<String> {
519 cx.sess().source_map().span_to_snippet(span).ok()
522 /// Converts a span (from a block) to a code snippet if available, otherwise use default.
524 /// This trims the code of indentation, except for the first line. Use it for blocks or block-like
525 /// things which need to be printed as such.
527 /// The `indent_relative_to` arg can be used, to provide a span, where the indentation of the
528 /// resulting snippet of the given span.
533 /// snippet_block(cx, block.span, "..", None)
534 /// // where, `block` is the block of the if expr
538 /// // will return the snippet
545 /// snippet_block(cx, block.span, "..", Some(if_expr.span))
546 /// // where, `block` is the block of the if expr
550 /// // will return the snippet
553 /// } // aligned with `if`
555 /// Note that the first line of the snippet always has 0 indentation.
556 pub fn snippet_block<'a, T: LintContext>(
560 indent_relative_to: Option<Span>,
562 let snip = snippet(cx, span, default);
563 let indent = indent_relative_to.and_then(|s| indent_of(cx, s));
564 trim_multiline(snip, true, indent)
567 /// Same as `snippet_block`, but adapts the applicability level by the rules of
568 /// `snippet_with_applicabiliy`.
569 pub fn snippet_block_with_applicability<'a, T: LintContext>(
573 indent_relative_to: Option<Span>,
574 applicability: &mut Applicability,
576 let snip = snippet_with_applicability(cx, span, default, applicability);
577 let indent = indent_relative_to.and_then(|s| indent_of(cx, s));
578 trim_multiline(snip, true, indent)
581 /// Returns a new Span that extends the original Span to the first non-whitespace char of the first
587 /// // will be converted to
591 pub fn first_line_of_span<T: LintContext>(cx: &T, span: Span) -> Span {
592 first_char_in_first_line(cx, span).map_or(span, |first_char_pos| span.with_lo(first_char_pos))
595 fn first_char_in_first_line<T: LintContext>(cx: &T, span: Span) -> Option<BytePos> {
596 let line_span = line_span(cx, span);
597 snippet_opt(cx, line_span).and_then(|snip| {
598 snip.find(|c: char| !c.is_whitespace())
599 .map(|pos| line_span.lo() + BytePos::from_usize(pos))
603 /// Returns the indentation of the line of a span
607 /// // ^^ -- will return 0
609 /// // ^^ -- will return 4
611 pub fn indent_of<T: LintContext>(cx: &T, span: Span) -> Option<usize> {
612 snippet_opt(cx, line_span(cx, span)).and_then(|snip| snip.find(|c: char| !c.is_whitespace()))
615 /// Extends the span to the beginning of the spans line, incl. whitespaces.
620 /// // will be converted to
622 /// // ^^^^^^^^^^^^^^
624 fn line_span<T: LintContext>(cx: &T, span: Span) -> Span {
625 let span = original_sp(span, DUMMY_SP);
626 let source_map_and_line = cx.sess().source_map().lookup_line(span.lo()).unwrap();
627 let line_no = source_map_and_line.line;
628 let line_start = source_map_and_line.sf.lines[line_no];
629 Span::new(line_start, span.hi(), span.ctxt())
632 /// Like `snippet_block`, but add braces if the expr is not an `ExprKind::Block`.
633 /// Also takes an `Option<String>` which can be put inside the braces.
634 pub fn expr_block<'a, T: LintContext>(
637 option: Option<String>,
639 indent_relative_to: Option<Span>,
641 let code = snippet_block(cx, expr.span, default, indent_relative_to);
642 let string = option.unwrap_or_default();
643 if expr.span.from_expansion() {
644 Cow::Owned(format!("{{ {} }}", snippet_with_macro_callsite(cx, expr.span, default)))
645 } else if let ExprKind::Block(_, _) = expr.kind {
646 Cow::Owned(format!("{}{}", code, string))
647 } else if string.is_empty() {
648 Cow::Owned(format!("{{ {} }}", code))
650 Cow::Owned(format!("{{\n{};\n{}\n}}", code, string))
654 /// Trim indentation from a multiline string with possibility of ignoring the
656 fn trim_multiline(s: Cow<'_, str>, ignore_first: bool, indent: Option<usize>) -> Cow<'_, str> {
657 let s_space = trim_multiline_inner(s, ignore_first, indent, ' ');
658 let s_tab = trim_multiline_inner(s_space, ignore_first, indent, '\t');
659 trim_multiline_inner(s_tab, ignore_first, indent, ' ')
662 fn trim_multiline_inner(s: Cow<'_, str>, ignore_first: bool, indent: Option<usize>, ch: char) -> Cow<'_, str> {
665 .skip(ignore_first as usize)
670 // ignore empty lines
671 Some(l.char_indices().find(|&(_, x)| x != ch).unwrap_or((l.len(), ch)).0)
676 if let Some(indent) = indent {
677 x = x.saturating_sub(indent);
684 if (ignore_first && i == 0) || l.is_empty() {
698 /// Gets the parent expression, if any –- this is useful to constrain a lint.
699 pub fn get_parent_expr<'c>(cx: &'c LateContext<'_>, e: &Expr<'_>) -> Option<&'c Expr<'c>> {
700 let map = &cx.tcx.hir();
701 let hir_id = e.hir_id;
702 let parent_id = map.get_parent_node(hir_id);
703 if hir_id == parent_id {
706 map.find(parent_id).and_then(|node| {
707 if let Node::Expr(parent) = node {
715 pub fn get_enclosing_block<'tcx>(cx: &LateContext<'tcx>, hir_id: HirId) -> Option<&'tcx Block<'tcx>> {
716 let map = &cx.tcx.hir();
717 let enclosing_node = map
718 .get_enclosing_scope(hir_id)
719 .and_then(|enclosing_id| map.find(enclosing_id));
720 enclosing_node.and_then(|node| match node {
721 Node::Block(block) => Some(block),
723 kind: ItemKind::Fn(_, _, eid),
726 | Node::ImplItem(&ImplItem {
727 kind: ImplItemKind::Fn(_, eid),
729 }) => match cx.tcx.hir().body(eid).value.kind {
730 ExprKind::Block(ref block, _) => Some(block),
737 /// Returns the base type for HIR references and pointers.
738 pub fn walk_ptrs_hir_ty<'tcx>(ty: &'tcx hir::Ty<'tcx>) -> &'tcx hir::Ty<'tcx> {
740 TyKind::Ptr(ref mut_ty) | TyKind::Rptr(_, ref mut_ty) => walk_ptrs_hir_ty(&mut_ty.ty),
745 /// Returns the base type for references and raw pointers.
746 pub fn walk_ptrs_ty(ty: Ty<'_>) -> Ty<'_> {
748 ty::Ref(_, ty, _) => walk_ptrs_ty(ty),
753 /// Returns the base type for references and raw pointers, and count reference
755 pub fn walk_ptrs_ty_depth(ty: Ty<'_>) -> (Ty<'_>, usize) {
756 fn inner(ty: Ty<'_>, depth: usize) -> (Ty<'_>, usize) {
758 ty::Ref(_, ty, _) => inner(ty, depth + 1),
765 /// Checks whether the given expression is a constant integer of the given value.
766 /// unlike `is_integer_literal`, this version does const folding
767 pub fn is_integer_const(cx: &LateContext<'_>, e: &Expr<'_>, value: u128) -> bool {
768 if is_integer_literal(e, value) {
771 let map = cx.tcx.hir();
772 let parent_item = map.get_parent_item(e.hir_id);
773 if let Some((Constant::Int(v), _)) = map
774 .maybe_body_owned_by(parent_item)
775 .and_then(|body_id| constant(cx, cx.tcx.body_tables(body_id), e))
783 /// Checks whether the given expression is a constant literal of the given value.
784 pub fn is_integer_literal(expr: &Expr<'_>, value: u128) -> bool {
785 // FIXME: use constant folding
786 if let ExprKind::Lit(ref spanned) = expr.kind {
787 if let LitKind::Int(v, _) = spanned.node {
794 /// Returns `true` if the given `Expr` has been coerced before.
796 /// Examples of coercions can be found in the Nomicon at
797 /// <https://doc.rust-lang.org/nomicon/coercions.html>.
799 /// See `rustc_middle::ty::adjustment::Adjustment` and `rustc_typeck::check::coercion` for more
800 /// information on adjustments and coercions.
801 pub fn is_adjusted(cx: &LateContext<'_>, e: &Expr<'_>) -> bool {
802 cx.tables().adjustments().get(e.hir_id).is_some()
805 /// Returns the pre-expansion span if is this comes from an expansion of the
807 /// See also `is_direct_expn_of`.
809 pub fn is_expn_of(mut span: Span, name: &str) -> Option<Span> {
811 if span.from_expansion() {
812 let data = span.ctxt().outer_expn_data();
813 let new_span = data.call_site;
815 if let ExpnKind::Macro(MacroKind::Bang, mac_name) = data.kind {
816 if mac_name.as_str() == name {
817 return Some(new_span);
828 /// Returns the pre-expansion span if the span directly comes from an expansion
829 /// of the macro `name`.
830 /// The difference with `is_expn_of` is that in
834 /// `42` is considered expanded from `foo!` and `bar!` by `is_expn_of` but only
836 /// `is_direct_expn_of`.
838 pub fn is_direct_expn_of(span: Span, name: &str) -> Option<Span> {
839 if span.from_expansion() {
840 let data = span.ctxt().outer_expn_data();
841 let new_span = data.call_site;
843 if let ExpnKind::Macro(MacroKind::Bang, mac_name) = data.kind {
844 if mac_name.as_str() == name {
845 return Some(new_span);
853 /// Convenience function to get the return type of a function.
854 pub fn return_ty<'tcx>(cx: &LateContext<'tcx>, fn_item: hir::HirId) -> Ty<'tcx> {
855 let fn_def_id = cx.tcx.hir().local_def_id(fn_item);
856 let ret_ty = cx.tcx.fn_sig(fn_def_id).output();
857 cx.tcx.erase_late_bound_regions(&ret_ty)
860 /// Returns `true` if the given type is an `unsafe` function.
861 pub fn type_is_unsafe_function<'tcx>(cx: &LateContext<'tcx>, ty: Ty<'tcx>) -> bool {
863 ty::FnDef(..) | ty::FnPtr(_) => ty.fn_sig(cx.tcx).unsafety() == Unsafety::Unsafe,
868 pub fn is_copy<'tcx>(cx: &LateContext<'tcx>, ty: Ty<'tcx>) -> bool {
869 ty.is_copy_modulo_regions(cx.tcx.at(DUMMY_SP), cx.param_env)
872 /// Checks if an expression is constructing a tuple-like enum variant or struct
873 pub fn is_ctor_or_promotable_const_function(cx: &LateContext<'_>, expr: &Expr<'_>) -> bool {
874 if let ExprKind::Call(ref fun, _) = expr.kind {
875 if let ExprKind::Path(ref qp) = fun.kind {
876 let res = cx.qpath_res(qp, fun.hir_id);
878 def::Res::Def(DefKind::Variant | DefKind::Ctor(..), ..) => true,
879 def::Res::Def(_, def_id) => cx.tcx.is_promotable_const_fn(def_id),
887 /// Returns `true` if a pattern is refutable.
888 // TODO: should be implemented using rustc/mir_build/hair machinery
889 pub fn is_refutable(cx: &LateContext<'_>, pat: &Pat<'_>) -> bool {
890 fn is_enum_variant(cx: &LateContext<'_>, qpath: &QPath<'_>, id: HirId) -> bool {
892 cx.qpath_res(qpath, id),
893 def::Res::Def(DefKind::Variant, ..) | Res::Def(DefKind::Ctor(def::CtorOf::Variant, _), _)
897 fn are_refutable<'a, I: Iterator<Item = &'a Pat<'a>>>(cx: &LateContext<'_>, mut i: I) -> bool {
898 i.any(|pat| is_refutable(cx, pat))
902 PatKind::Wild => false,
903 PatKind::Binding(_, _, _, pat) => pat.map_or(false, |pat| is_refutable(cx, pat)),
904 PatKind::Box(ref pat) | PatKind::Ref(ref pat, _) => is_refutable(cx, pat),
905 PatKind::Lit(..) | PatKind::Range(..) => true,
906 PatKind::Path(ref qpath) => is_enum_variant(cx, qpath, pat.hir_id),
907 PatKind::Or(ref pats) => {
908 // TODO: should be the honest check, that pats is exhaustive set
909 are_refutable(cx, pats.iter().map(|pat| &**pat))
911 PatKind::Tuple(ref pats, _) => are_refutable(cx, pats.iter().map(|pat| &**pat)),
912 PatKind::Struct(ref qpath, ref fields, _) => {
913 is_enum_variant(cx, qpath, pat.hir_id) || are_refutable(cx, fields.iter().map(|field| &*field.pat))
915 PatKind::TupleStruct(ref qpath, ref pats, _) => {
916 is_enum_variant(cx, qpath, pat.hir_id) || are_refutable(cx, pats.iter().map(|pat| &**pat))
918 PatKind::Slice(ref head, ref middle, ref tail) => {
919 match &cx.tables().node_type(pat.hir_id).kind {
921 // [..] is the only irrefutable slice pattern.
922 !head.is_empty() || middle.is_none() || !tail.is_empty()
924 ty::Array(..) => are_refutable(cx, head.iter().chain(middle).chain(tail.iter()).map(|pat| &**pat)),
934 /// Checks for the `#[automatically_derived]` attribute all `#[derive]`d
935 /// implementations have.
936 pub fn is_automatically_derived(attrs: &[ast::Attribute]) -> bool {
937 attr::contains_name(attrs, sym!(automatically_derived))
940 /// Remove blocks around an expression.
942 /// Ie. `x`, `{ x }` and `{{{{ x }}}}` all give `x`. `{ x; y }` and `{}` return
944 pub fn remove_blocks<'tcx>(mut expr: &'tcx Expr<'tcx>) -> &'tcx Expr<'tcx> {
945 while let ExprKind::Block(ref block, ..) = expr.kind {
946 match (block.stmts.is_empty(), block.expr.as_ref()) {
947 (true, Some(e)) => expr = e,
954 pub fn is_self(slf: &Param<'_>) -> bool {
955 if let PatKind::Binding(.., name, _) = slf.pat.kind {
956 name.name == kw::SelfLower
962 pub fn is_self_ty(slf: &hir::Ty<'_>) -> bool {
964 if let TyKind::Path(ref qp) = slf.kind;
965 if let QPath::Resolved(None, ref path) = *qp;
966 if let Res::SelfTy(..) = path.res;
974 pub fn iter_input_pats<'tcx>(decl: &FnDecl<'_>, body: &'tcx Body<'_>) -> impl Iterator<Item = &'tcx Param<'tcx>> {
975 (0..decl.inputs.len()).map(move |i| &body.params[i])
978 /// Checks if a given expression is a match expression expanded from the `?`
979 /// operator or the `try` macro.
980 pub fn is_try<'tcx>(expr: &'tcx Expr<'tcx>) -> Option<&'tcx Expr<'tcx>> {
981 fn is_ok(arm: &Arm<'_>) -> bool {
983 if let PatKind::TupleStruct(ref path, ref pat, None) = arm.pat.kind;
984 if match_qpath(path, &paths::RESULT_OK[1..]);
985 if let PatKind::Binding(_, hir_id, _, None) = pat[0].kind;
986 if let ExprKind::Path(QPath::Resolved(None, ref path)) = arm.body.kind;
987 if let Res::Local(lid) = path.res;
996 fn is_err(arm: &Arm<'_>) -> bool {
997 if let PatKind::TupleStruct(ref path, _, _) = arm.pat.kind {
998 match_qpath(path, &paths::RESULT_ERR[1..])
1004 if let ExprKind::Match(_, ref arms, ref source) = expr.kind {
1005 // desugared from a `?` operator
1006 if let MatchSource::TryDesugar = *source {
1012 if arms[0].guard.is_none();
1013 if arms[1].guard.is_none();
1014 if (is_ok(&arms[0]) && is_err(&arms[1])) ||
1015 (is_ok(&arms[1]) && is_err(&arms[0]));
1025 /// Returns `true` if the lint is allowed in the current context
1027 /// Useful for skipping long running code when it's unnecessary
1028 pub fn is_allowed(cx: &LateContext<'_>, lint: &'static Lint, id: HirId) -> bool {
1029 cx.tcx.lint_level_at_node(lint, id).0 == Level::Allow
1032 pub fn get_arg_name(pat: &Pat<'_>) -> Option<Name> {
1034 PatKind::Binding(.., ident, None) => Some(ident.name),
1035 PatKind::Ref(ref subpat, _) => get_arg_name(subpat),
1040 pub fn int_bits(tcx: TyCtxt<'_>, ity: ast::IntTy) -> u64 {
1041 Integer::from_attr(&tcx, attr::IntType::SignedInt(ity)).size().bits()
1044 #[allow(clippy::cast_possible_wrap)]
1045 /// Turn a constant int byte representation into an i128
1046 pub fn sext(tcx: TyCtxt<'_>, u: u128, ity: ast::IntTy) -> i128 {
1047 let amt = 128 - int_bits(tcx, ity);
1048 ((u as i128) << amt) >> amt
1051 #[allow(clippy::cast_sign_loss)]
1052 /// clip unused bytes
1053 pub fn unsext(tcx: TyCtxt<'_>, u: i128, ity: ast::IntTy) -> u128 {
1054 let amt = 128 - int_bits(tcx, ity);
1055 ((u as u128) << amt) >> amt
1058 /// clip unused bytes
1059 pub fn clip(tcx: TyCtxt<'_>, u: u128, ity: ast::UintTy) -> u128 {
1060 let bits = Integer::from_attr(&tcx, attr::IntType::UnsignedInt(ity)).size().bits();
1061 let amt = 128 - bits;
1065 /// Removes block comments from the given `Vec` of lines.
1070 /// without_block_comments(vec!["/*", "foo", "*/"]);
1073 /// without_block_comments(vec!["bar", "/*", "foo", "*/"]);
1074 /// // => vec!["bar"]
1076 pub fn without_block_comments(lines: Vec<&str>) -> Vec<&str> {
1077 let mut without = vec![];
1079 let mut nest_level = 0;
1082 if line.contains("/*") {
1085 } else if line.contains("*/") {
1090 if nest_level == 0 {
1098 pub fn any_parent_is_automatically_derived(tcx: TyCtxt<'_>, node: HirId) -> bool {
1099 let map = &tcx.hir();
1100 let mut prev_enclosing_node = None;
1101 let mut enclosing_node = node;
1102 while Some(enclosing_node) != prev_enclosing_node {
1103 if is_automatically_derived(map.attrs(enclosing_node)) {
1106 prev_enclosing_node = Some(enclosing_node);
1107 enclosing_node = map.get_parent_item(enclosing_node);
1112 /// Returns true if ty has `iter` or `iter_mut` methods
1113 pub fn has_iter_method(cx: &LateContext<'_>, probably_ref_ty: Ty<'_>) -> Option<&'static str> {
1114 // FIXME: instead of this hard-coded list, we should check if `<adt>::iter`
1115 // exists and has the desired signature. Unfortunately FnCtxt is not exported
1116 // so we can't use its `lookup_method` method.
1117 let into_iter_collections: [&[&str]; 13] = [
1124 &paths::LINKED_LIST,
1125 &paths::BINARY_HEAP,
1133 let ty_to_check = match probably_ref_ty.kind {
1134 ty::Ref(_, ty_to_check, _) => ty_to_check,
1135 _ => probably_ref_ty,
1138 let def_id = match ty_to_check.kind {
1139 ty::Array(..) => return Some("array"),
1140 ty::Slice(..) => return Some("slice"),
1141 ty::Adt(adt, _) => adt.did,
1145 for path in &into_iter_collections {
1146 if match_def_path(cx, def_id, path) {
1147 return Some(*path.last().unwrap());
1153 /// Matches a function call with the given path and returns the arguments.
1158 /// if let Some(args) = match_function_call(cx, begin_panic_call, &paths::BEGIN_PANIC);
1160 pub fn match_function_call<'tcx>(
1161 cx: &LateContext<'tcx>,
1162 expr: &'tcx Expr<'_>,
1164 ) -> Option<&'tcx [Expr<'tcx>]> {
1166 if let ExprKind::Call(ref fun, ref args) = expr.kind;
1167 if let ExprKind::Path(ref qpath) = fun.kind;
1168 if let Some(fun_def_id) = cx.qpath_res(qpath, fun.hir_id).opt_def_id();
1169 if match_def_path(cx, fun_def_id, path);
1177 /// Checks if `Ty` is normalizable. This function is useful
1178 /// to avoid crashes on `layout_of`.
1179 pub fn is_normalizable<'tcx>(cx: &LateContext<'tcx>, param_env: ty::ParamEnv<'tcx>, ty: Ty<'tcx>) -> bool {
1180 cx.tcx.infer_ctxt().enter(|infcx| {
1181 let cause = rustc_middle::traits::ObligationCause::dummy();
1182 infcx.at(&cause, param_env).normalize(&ty).is_ok()
1186 pub fn match_def_path<'tcx>(cx: &LateContext<'tcx>, did: DefId, syms: &[&str]) -> bool {
1187 // We have to convert `syms` to `&[Symbol]` here because rustc's `match_def_path`
1188 // accepts only that. We should probably move to Symbols in Clippy as well.
1189 let syms = syms.iter().map(|p| Symbol::intern(p)).collect::<Vec<Symbol>>();
1190 cx.match_def_path(did, &syms)
1193 /// Returns the list of condition expressions and the list of blocks in a
1194 /// sequence of `if/else`.
1195 /// E.g., this returns `([a, b], [c, d, e])` for the expression
1196 /// `if a { c } else if b { d } else { e }`.
1197 pub fn if_sequence<'tcx>(
1198 mut expr: &'tcx Expr<'tcx>,
1199 ) -> (SmallVec<[&'tcx Expr<'tcx>; 1]>, SmallVec<[&'tcx Block<'tcx>; 1]>) {
1200 let mut conds = SmallVec::new();
1201 let mut blocks: SmallVec<[&Block<'_>; 1]> = SmallVec::new();
1203 while let Some((ref cond, ref then_expr, ref else_expr)) = higher::if_block(&expr) {
1204 conds.push(&**cond);
1205 if let ExprKind::Block(ref block, _) = then_expr.kind {
1208 panic!("ExprKind::If node is not an ExprKind::Block");
1211 if let Some(ref else_expr) = *else_expr {
1218 // final `else {..}`
1219 if !blocks.is_empty() {
1220 if let ExprKind::Block(ref block, _) = expr.kind {
1221 blocks.push(&**block);
1228 pub fn parent_node_is_if_expr(expr: &Expr<'_>, cx: &LateContext<'_>) -> bool {
1229 let map = cx.tcx.hir();
1230 let parent_id = map.get_parent_node(expr.hir_id);
1231 let parent_node = map.get(parent_id);
1234 Node::Expr(e) => higher::if_block(&e).is_some(),
1235 Node::Arm(e) => higher::if_block(&e.body).is_some(),
1240 // Finds the attribute with the given name, if any
1241 pub fn attr_by_name<'a>(attrs: &'a [Attribute], name: &'_ str) -> Option<&'a Attribute> {
1244 .find(|attr| attr.ident().map_or(false, |ident| ident.as_str() == name))
1247 // Finds the `#[must_use]` attribute, if any
1248 pub fn must_use_attr(attrs: &[Attribute]) -> Option<&Attribute> {
1249 attr_by_name(attrs, "must_use")
1252 // Returns whether the type has #[must_use] attribute
1253 pub fn is_must_use_ty<'tcx>(cx: &LateContext<'tcx>, ty: Ty<'tcx>) -> bool {
1255 ty::Adt(ref adt, _) => must_use_attr(&cx.tcx.get_attrs(adt.did)).is_some(),
1256 ty::Foreign(ref did) => must_use_attr(&cx.tcx.get_attrs(*did)).is_some(),
1258 | ty::Array(ref ty, _)
1259 | ty::RawPtr(ty::TypeAndMut { ref ty, .. })
1260 | ty::Ref(_, ref ty, _) => {
1261 // for the Array case we don't need to care for the len == 0 case
1262 // because we don't want to lint functions returning empty arrays
1263 is_must_use_ty(cx, *ty)
1265 ty::Tuple(ref substs) => substs.types().any(|ty| is_must_use_ty(cx, ty)),
1266 ty::Opaque(ref def_id, _) => {
1267 for (predicate, _) in cx.tcx.predicates_of(*def_id).predicates {
1268 if let ty::PredicateKind::Trait(ref poly_trait_predicate, _) = predicate.kind() {
1269 if must_use_attr(&cx.tcx.get_attrs(poly_trait_predicate.skip_binder().trait_ref.def_id)).is_some() {
1276 ty::Dynamic(binder, _) => {
1277 for predicate in binder.skip_binder().iter() {
1278 if let ty::ExistentialPredicate::Trait(ref trait_ref) = predicate {
1279 if must_use_attr(&cx.tcx.get_attrs(trait_ref.def_id)).is_some() {
1290 // check if expr is calling method or function with #[must_use] attribyte
1291 pub fn is_must_use_func_call(cx: &LateContext<'_>, expr: &Expr<'_>) -> bool {
1292 let did = match expr.kind {
1293 ExprKind::Call(ref path, _) => if_chain! {
1294 if let ExprKind::Path(ref qpath) = path.kind;
1295 if let def::Res::Def(_, did) = cx.qpath_res(qpath, path.hir_id);
1302 ExprKind::MethodCall(_, _, _, _) => cx.tables().type_dependent_def_id(expr.hir_id),
1306 did.map_or(false, |did| must_use_attr(&cx.tcx.get_attrs(did)).is_some())
1309 pub fn is_no_std_crate(krate: &Crate<'_>) -> bool {
1310 krate.item.attrs.iter().any(|attr| {
1311 if let ast::AttrKind::Normal(ref attr) = attr.kind {
1312 attr.path == symbol::sym::no_std
1319 /// Check if parent of a hir node is a trait implementation block.
1320 /// For example, `f` in
1322 /// impl Trait for S {
1326 pub fn is_trait_impl_item(cx: &LateContext<'_>, hir_id: HirId) -> bool {
1327 if let Some(Node::Item(item)) = cx.tcx.hir().find(cx.tcx.hir().get_parent_node(hir_id)) {
1328 matches!(item.kind, ItemKind::Impl{ of_trait: Some(_), .. })
1334 /// Check if it's even possible to satisfy the `where` clause for the item.
1336 /// `trivial_bounds` feature allows functions with unsatisfiable bounds, for example:
1339 /// fn foo() where i32: Iterator {
1340 /// for _ in 2i32 {}
1343 pub fn fn_has_unsatisfiable_preds(cx: &LateContext<'_>, did: DefId) -> bool {
1344 use rustc_trait_selection::traits;
1350 .filter_map(|(p, _)| if p.is_global() { Some(*p) } else { None });
1351 !traits::normalize_and_test_predicates(
1353 traits::elaborate_predicates(cx.tcx, predicates)
1354 .map(|o| o.predicate)
1355 .collect::<Vec<_>>(),
1359 /// Returns the `DefId` of the callee if the given expression is a function or method call.
1360 pub fn fn_def_id(cx: &LateContext<'_>, expr: &Expr<'_>) -> Option<DefId> {
1362 ExprKind::MethodCall(..) => cx.tables().type_dependent_def_id(expr.hir_id),
1365 kind: ExprKind::Path(qpath),
1369 ) => cx.tables().qpath_res(qpath, expr.hir_id).opt_def_id(),
1374 pub fn run_lints(cx: &LateContext<'_>, lints: &[&'static Lint], id: HirId) -> bool {
1375 lints.iter().any(|lint| {
1377 cx.tcx.lint_level_at_node(lint, id),
1378 (Level::Forbid | Level::Deny | Level::Warn, _)
1384 macro_rules! unwrap_cargo_metadata {
1385 ($cx: ident, $lint: ident, $deps: expr) => {{
1386 let mut command = cargo_metadata::MetadataCommand::new();
1391 match command.exec() {
1392 Ok(metadata) => metadata,
1394 span_lint($cx, $lint, DUMMY_SP, &format!("could not read cargo metadata: {}", err));
1403 use super::{trim_multiline, without_block_comments};
1406 fn test_trim_multiline_single_line() {
1407 assert_eq!("", trim_multiline("".into(), false, None));
1408 assert_eq!("...", trim_multiline("...".into(), false, None));
1409 assert_eq!("...", trim_multiline(" ...".into(), false, None));
1410 assert_eq!("...", trim_multiline("\t...".into(), false, None));
1411 assert_eq!("...", trim_multiline("\t\t...".into(), false, None));
1416 fn test_trim_multiline_block() {
1422 }", trim_multiline(" if x {
1426 }".into(), false, None));
1432 }", trim_multiline(" if x {
1436 }".into(), false, None));
1441 fn test_trim_multiline_empty_line() {
1448 }", trim_multiline(" if x {
1453 }".into(), false, None));
1457 fn test_without_block_comments_lines_without_block_comments() {
1458 let result = without_block_comments(vec!["/*", "", "*/"]);
1459 println!("result: {:?}", result);
1460 assert!(result.is_empty());
1462 let result = without_block_comments(vec!["", "/*", "", "*/", "#[crate_type = \"lib\"]", "/*", "", "*/", ""]);
1463 assert_eq!(result, vec!["", "#[crate_type = \"lib\"]", ""]);
1465 let result = without_block_comments(vec!["/* rust", "", "*/"]);
1466 assert!(result.is_empty());
1468 let result = without_block_comments(vec!["/* one-line comment */"]);
1469 assert!(result.is_empty());
1471 let result = without_block_comments(vec!["/* nested", "/* multi-line", "comment", "*/", "test", "*/"]);
1472 assert!(result.is_empty());
1474 let result = without_block_comments(vec!["/* nested /* inline /* comment */ test */ */"]);
1475 assert!(result.is_empty());
1477 let result = without_block_comments(vec!["foo", "bar", "baz"]);
1478 assert_eq!(result, vec!["foo", "bar", "baz"]);