1 #![feature(box_patterns)]
2 #![feature(in_band_lifetimes)]
3 #![feature(or_patterns)]
4 #![feature(rustc_private)]
5 #![recursion_limit = "512"]
6 #![allow(clippy::missing_errors_doc, clippy::missing_panics_doc, clippy::must_use_candidate)]
8 // FIXME: switch to something more ergonomic here, once available.
9 // (Currently there is no way to opt into sysroot crates without `extern crate`.)
10 extern crate rustc_ast;
11 extern crate rustc_ast_pretty;
12 extern crate rustc_data_structures;
13 extern crate rustc_errors;
14 extern crate rustc_hir;
15 extern crate rustc_hir_pretty;
16 extern crate rustc_infer;
17 extern crate rustc_lexer;
18 extern crate rustc_lint;
19 extern crate rustc_middle;
20 extern crate rustc_mir;
21 extern crate rustc_session;
22 extern crate rustc_span;
23 extern crate rustc_target;
24 extern crate rustc_trait_selection;
25 extern crate rustc_typeck;
30 #[allow(clippy::module_name_repetitions)]
37 pub mod eager_or_lazy;
40 pub mod numeric_literal;
43 pub mod qualify_min_const_fn;
49 pub use self::attrs::*;
50 pub use self::diagnostics::*;
51 pub use self::hir_utils::{both, eq_expr_value, over, SpanlessEq, SpanlessHash};
54 use std::collections::hash_map::Entry;
55 use std::hash::BuildHasherDefault;
57 use if_chain::if_chain;
58 use rustc_ast::ast::{self, Attribute, BorrowKind, LitKind};
59 use rustc_data_structures::fx::FxHashMap;
60 use rustc_errors::Applicability;
62 use rustc_hir::def::{CtorKind, CtorOf, DefKind, Res};
63 use rustc_hir::def_id::{DefId, LOCAL_CRATE};
64 use rustc_hir::intravisit::{self, NestedVisitorMap, Visitor};
66 def, Arm, BindingAnnotation, Block, Body, Constness, CrateItem, Expr, ExprKind, FnDecl, ForeignItem, GenericArgs,
67 GenericParam, HirId, Impl, ImplItem, ImplItemKind, Item, ItemKind, LangItem, Lifetime, Local, MacroDef,
68 MatchSource, Node, Param, Pat, PatKind, Path, PathSegment, QPath, Stmt, StructField, TraitItem, TraitItemKind,
69 TraitRef, TyKind, Variant, Visibility,
71 use rustc_lint::{LateContext, Level, Lint, LintContext};
72 use rustc_middle::hir::exports::Export;
73 use rustc_middle::hir::map::Map;
74 use rustc_middle::ty as rustc_ty;
75 use rustc_middle::ty::{layout::IntegerExt, DefIdTree, Ty, TyCtxt, TypeFoldable};
76 use rustc_semver::RustcVersion;
77 use rustc_session::Session;
78 use rustc_span::hygiene::{self, ExpnKind, MacroKind};
79 use rustc_span::source_map::original_sp;
81 use rustc_span::symbol::{kw, Ident, Symbol};
82 use rustc_span::{BytePos, Pos, Span, SyntaxContext, DUMMY_SP};
83 use rustc_target::abi::Integer;
84 use smallvec::SmallVec;
86 use crate::consts::{constant, Constant};
87 use crate::ty::is_recursively_primitive_type;
89 pub fn parse_msrv(msrv: &str, sess: Option<&Session>, span: Option<Span>) -> Option<RustcVersion> {
90 if let Ok(version) = RustcVersion::parse(msrv) {
92 } else if let Some(sess) = sess {
93 if let Some(span) = span {
94 sess.span_err(span, &format!("`{}` is not a valid Rust version", msrv));
100 pub fn meets_msrv(msrv: Option<&RustcVersion>, lint_msrv: &RustcVersion) -> bool {
101 msrv.map_or(true, |msrv| msrv.meets(*lint_msrv))
105 macro_rules! extract_msrv_attr {
107 extract_msrv_attr!(@LateContext, ());
110 extract_msrv_attr!(@EarlyContext);
112 (@$context:ident$(, $call:tt)?) => {
113 fn enter_lint_attrs(&mut self, cx: &rustc_lint::$context<'tcx>, attrs: &'tcx [rustc_ast::ast::Attribute]) {
114 use $crate::get_unique_inner_attr;
115 match get_unique_inner_attr(cx.sess$($call)?, attrs, "msrv") {
117 if let Some(msrv) = msrv_attr.value_str() {
118 self.msrv = $crate::parse_msrv(
120 Some(cx.sess$($call)?),
121 Some(msrv_attr.span),
124 cx.sess$($call)?.span_err(msrv_attr.span, "bad clippy attribute");
133 /// Returns `true` if the two spans come from differing expansions (i.e., one is
134 /// from a macro and one isn't).
136 pub fn differing_macro_contexts(lhs: Span, rhs: Span) -> bool {
137 rhs.ctxt() != lhs.ctxt()
140 /// If the given expression is a local binding, find the initializer expression.
141 /// If that initializer expression is another local binding, find its initializer again.
142 /// This process repeats as long as possible (but usually no more than once). Initializer
143 /// expressions with adjustments are ignored. If this is not desired, use [`find_binding_init`]
156 /// let def = abc + 2;
157 /// // ^^^^^^^ output
161 pub fn expr_or_init<'a, 'b, 'tcx: 'b>(cx: &LateContext<'tcx>, mut expr: &'a Expr<'b>) -> &'a Expr<'b> {
162 while let Some(init) = path_to_local(expr)
163 .and_then(|id| find_binding_init(cx, id))
164 .filter(|init| cx.typeck_results().expr_adjustments(init).is_empty())
171 /// Finds the initializer expression for a local binding. Returns `None` if the binding is mutable.
172 /// By only considering immutable bindings, we guarantee that the returned expression represents the
173 /// value of the binding wherever it is referenced.
175 /// Example: For `let x = 1`, if the `HirId` of `x` is provided, the `Expr` `1` is returned.
176 /// Note: If you have an expression that references a binding `x`, use `path_to_local` to get the
177 /// canonical binding `HirId`.
178 pub fn find_binding_init<'tcx>(cx: &LateContext<'tcx>, hir_id: HirId) -> Option<&'tcx Expr<'tcx>> {
179 let hir = cx.tcx.hir();
181 if let Some(Node::Binding(pat)) = hir.find(hir_id);
182 if matches!(pat.kind, PatKind::Binding(BindingAnnotation::Unannotated, ..));
183 let parent = hir.get_parent_node(hir_id);
184 if let Some(Node::Local(local)) = hir.find(parent);
192 /// Returns `true` if the given `NodeId` is inside a constant context
197 /// if in_constant(cx, expr.hir_id) {
201 pub fn in_constant(cx: &LateContext<'_>, id: HirId) -> bool {
202 let parent_id = cx.tcx.hir().get_parent_item(id);
203 match cx.tcx.hir().get(parent_id) {
205 kind: ItemKind::Const(..) | ItemKind::Static(..),
208 | Node::TraitItem(&TraitItem {
209 kind: TraitItemKind::Const(..),
212 | Node::ImplItem(&ImplItem {
213 kind: ImplItemKind::Const(..),
216 | Node::AnonConst(_) => true,
218 kind: ItemKind::Fn(ref sig, ..),
221 | Node::ImplItem(&ImplItem {
222 kind: ImplItemKind::Fn(ref sig, _),
224 }) => sig.header.constness == Constness::Const,
229 /// Returns `true` if this `span` was expanded by any macro.
231 pub fn in_macro(span: Span) -> bool {
232 if span.from_expansion() {
233 !matches!(span.ctxt().outer_expn_data().kind, ExpnKind::Desugaring(..))
239 // If the snippet is empty, it's an attribute that was inserted during macro
240 // expansion and we want to ignore those, because they could come from external
241 // sources that the user has no control over.
242 // For some reason these attributes don't have any expansion info on them, so
243 // we have to check it this way until there is a better way.
244 pub fn is_present_in_source<T: LintContext>(cx: &T, span: Span) -> bool {
245 if let Some(snippet) = snippet_opt(cx, span) {
246 if snippet.is_empty() {
253 /// Checks if given pattern is a wildcard (`_`)
254 pub fn is_wild<'tcx>(pat: &impl std::ops::Deref<Target = Pat<'tcx>>) -> bool {
255 matches!(pat.kind, PatKind::Wild)
258 /// Checks if the first type parameter is a lang item.
259 pub fn is_ty_param_lang_item(cx: &LateContext<'_>, qpath: &QPath<'tcx>, item: LangItem) -> Option<&'tcx hir::Ty<'tcx>> {
260 let ty = get_qpath_generic_tys(qpath).next()?;
262 if let TyKind::Path(qpath) = &ty.kind {
263 cx.qpath_res(qpath, ty.hir_id)
265 .map_or(false, |id| {
266 cx.tcx.lang_items().require(item).map_or(false, |lang_id| id == lang_id)
274 /// Checks if the first type parameter is a diagnostic item.
275 pub fn is_ty_param_diagnostic_item(
276 cx: &LateContext<'_>,
279 ) -> Option<&'tcx hir::Ty<'tcx>> {
280 let ty = get_qpath_generic_tys(qpath).next()?;
282 if let TyKind::Path(qpath) = &ty.kind {
283 cx.qpath_res(qpath, ty.hir_id)
285 .map_or(false, |id| cx.tcx.is_diagnostic_item(item, id))
292 /// Checks if the method call given in `expr` belongs to the given trait.
293 /// This is a deprecated function, consider using [`is_trait_method`].
294 pub fn match_trait_method(cx: &LateContext<'_>, expr: &Expr<'_>, path: &[&str]) -> bool {
295 let def_id = cx.typeck_results().type_dependent_def_id(expr.hir_id).unwrap();
296 let trt_id = cx.tcx.trait_of_item(def_id);
297 trt_id.map_or(false, |trt_id| match_def_path(cx, trt_id, path))
300 /// Checks if the method call given in `def_id` belongs to a trait or other container with a given
302 pub fn is_diagnostic_assoc_item(cx: &LateContext<'_>, def_id: DefId, diag_item: Symbol) -> bool {
304 .opt_associated_item(def_id)
305 .and_then(|associated_item| match associated_item.container {
306 rustc_ty::TraitContainer(assoc_def_id) => Some(assoc_def_id),
307 rustc_ty::ImplContainer(assoc_def_id) => match cx.tcx.type_of(assoc_def_id).kind() {
308 rustc_ty::Adt(adt, _) => Some(adt.did),
309 rustc_ty::Slice(_) => cx.tcx.get_diagnostic_item(sym::slice), // this isn't perfect but it works
313 .map_or(false, |assoc_def_id| cx.tcx.is_diagnostic_item(diag_item, assoc_def_id))
316 /// Checks if the method call given in `expr` belongs to the given trait.
317 pub fn is_trait_method(cx: &LateContext<'_>, expr: &Expr<'_>, diag_item: Symbol) -> bool {
319 .type_dependent_def_id(expr.hir_id)
320 .map_or(false, |did| is_diagnostic_assoc_item(cx, did, diag_item))
323 /// Checks if an expression references a variable of the given name.
324 pub fn match_var(expr: &Expr<'_>, var: Symbol) -> bool {
325 if let ExprKind::Path(QPath::Resolved(None, ref path)) = expr.kind {
326 if let [p] = path.segments {
327 return p.ident.name == var;
333 pub fn last_path_segment<'tcx>(path: &QPath<'tcx>) -> &'tcx PathSegment<'tcx> {
335 QPath::Resolved(_, ref path) => path.segments.last().expect("A path must have at least one segment"),
336 QPath::TypeRelative(_, ref seg) => seg,
337 QPath::LangItem(..) => panic!("last_path_segment: lang item has no path segments"),
341 pub fn get_qpath_generics(path: &QPath<'tcx>) -> Option<&'tcx GenericArgs<'tcx>> {
343 QPath::Resolved(_, p) => p.segments.last().and_then(|s| s.args),
344 QPath::TypeRelative(_, s) => s.args,
345 QPath::LangItem(..) => None,
349 pub fn get_qpath_generic_tys(path: &QPath<'tcx>) -> impl Iterator<Item = &'tcx hir::Ty<'tcx>> {
350 get_qpath_generics(path)
351 .map_or([].as_ref(), |a| a.args)
354 if let hir::GenericArg::Type(ty) = a {
362 pub fn single_segment_path<'tcx>(path: &QPath<'tcx>) -> Option<&'tcx PathSegment<'tcx>> {
364 QPath::Resolved(_, ref path) => path.segments.get(0),
365 QPath::TypeRelative(_, ref seg) => Some(seg),
366 QPath::LangItem(..) => None,
370 /// Matches a `QPath` against a slice of segment string literals.
372 /// There is also `match_path` if you are dealing with a `rustc_hir::Path` instead of a
373 /// `rustc_hir::QPath`.
377 /// match_qpath(path, &["std", "rt", "begin_unwind"])
379 pub fn match_qpath(path: &QPath<'_>, segments: &[&str]) -> bool {
381 QPath::Resolved(_, ref path) => match_path(path, segments),
382 QPath::TypeRelative(ref ty, ref segment) => match ty.kind {
383 TyKind::Path(ref inner_path) => {
384 if let [prefix @ .., end] = segments {
385 if match_qpath(inner_path, prefix) {
386 return segment.ident.name.as_str() == *end;
393 QPath::LangItem(..) => false,
397 /// Matches a `Path` against a slice of segment string literals.
399 /// There is also `match_qpath` if you are dealing with a `rustc_hir::QPath` instead of a
400 /// `rustc_hir::Path`.
405 /// if match_path(&trait_ref.path, &paths::HASH) {
406 /// // This is the `std::hash::Hash` trait.
409 /// if match_path(ty_path, &["rustc", "lint", "Lint"]) {
410 /// // This is a `rustc_middle::lint::Lint`.
413 pub fn match_path(path: &Path<'_>, segments: &[&str]) -> bool {
417 .zip(segments.iter().rev())
418 .all(|(a, b)| a.ident.name.as_str() == *b)
421 /// Matches a `Path` against a slice of segment string literals, e.g.
425 /// match_path_ast(path, &["std", "rt", "begin_unwind"])
427 pub fn match_path_ast(path: &ast::Path, segments: &[&str]) -> bool {
431 .zip(segments.iter().rev())
432 .all(|(a, b)| a.ident.name.as_str() == *b)
435 /// If the expression is a path to a local, returns the canonical `HirId` of the local.
436 pub fn path_to_local(expr: &Expr<'_>) -> Option<HirId> {
437 if let ExprKind::Path(QPath::Resolved(None, ref path)) = expr.kind {
438 if let Res::Local(id) = path.res {
445 /// Returns true if the expression is a path to a local with the specified `HirId`.
446 /// Use this function to see if an expression matches a function argument or a match binding.
447 pub fn path_to_local_id(expr: &Expr<'_>, id: HirId) -> bool {
448 path_to_local(expr) == Some(id)
451 /// Gets the definition associated to a path.
452 #[allow(clippy::shadow_unrelated)] // false positive #6563
453 pub fn path_to_res(cx: &LateContext<'_>, path: &[&str]) -> Res {
454 macro_rules! try_res {
458 None => return Res::Err,
462 fn item_child_by_name<'tcx>(tcx: TyCtxt<'tcx>, def_id: DefId, name: &str) -> Option<&'tcx Export<HirId>> {
463 tcx.item_children(def_id)
465 .find(|item| item.ident.name.as_str() == name)
468 let (krate, first, path) = match *path {
469 [krate, first, ref path @ ..] => (krate, first, path),
470 _ => return Res::Err,
473 let crates = tcx.crates();
474 let krate = try_res!(crates.iter().find(|&&num| tcx.crate_name(num).as_str() == krate));
475 let first = try_res!(item_child_by_name(tcx, krate.as_def_id(), first));
479 // `get_def_path` seems to generate these empty segments for extern blocks.
480 // We can just ignore them.
481 .filter(|segment| !segment.is_empty())
482 // for each segment, find the child item
483 .try_fold(first, |item, segment| {
484 let def_id = item.res.def_id();
485 if let Some(item) = item_child_by_name(tcx, def_id, segment) {
487 } else if matches!(item.res, Res::Def(DefKind::Enum | DefKind::Struct, _)) {
488 // it is not a child item so check inherent impl items
489 tcx.inherent_impls(def_id)
491 .find_map(|&impl_def_id| item_child_by_name(tcx, impl_def_id, segment))
499 /// Convenience function to get the `DefId` of a trait by path.
500 /// It could be a trait or trait alias.
501 pub fn get_trait_def_id(cx: &LateContext<'_>, path: &[&str]) -> Option<DefId> {
502 match path_to_res(cx, path) {
503 Res::Def(DefKind::Trait | DefKind::TraitAlias, trait_id) => Some(trait_id),
508 /// Gets the `hir::TraitRef` of the trait the given method is implemented for.
510 /// Use this if you want to find the `TraitRef` of the `Add` trait in this example:
513 /// struct Point(isize, isize);
515 /// impl std::ops::Add for Point {
516 /// type Output = Self;
518 /// fn add(self, other: Self) -> Self {
523 pub fn trait_ref_of_method<'tcx>(cx: &LateContext<'tcx>, hir_id: HirId) -> Option<&'tcx TraitRef<'tcx>> {
524 // Get the implemented trait for the current function
525 let parent_impl = cx.tcx.hir().get_parent_item(hir_id);
527 if parent_impl != hir::CRATE_HIR_ID;
528 if let hir::Node::Item(item) = cx.tcx.hir().get(parent_impl);
529 if let hir::ItemKind::Impl(impl_) = &item.kind;
530 then { return impl_.of_trait.as_ref(); }
535 /// Returns the method names and argument list of nested method call expressions that make up
536 /// `expr`. method/span lists are sorted with the most recent call first.
537 pub fn method_calls<'tcx>(
538 expr: &'tcx Expr<'tcx>,
540 ) -> (Vec<Symbol>, Vec<&'tcx [Expr<'tcx>]>, Vec<Span>) {
541 let mut method_names = Vec::with_capacity(max_depth);
542 let mut arg_lists = Vec::with_capacity(max_depth);
543 let mut spans = Vec::with_capacity(max_depth);
545 let mut current = expr;
546 for _ in 0..max_depth {
547 if let ExprKind::MethodCall(path, span, args, _) = ¤t.kind {
548 if args.iter().any(|e| e.span.from_expansion()) {
551 method_names.push(path.ident.name);
552 arg_lists.push(&**args);
560 (method_names, arg_lists, spans)
563 /// Matches an `Expr` against a chain of methods, and return the matched `Expr`s.
565 /// For example, if `expr` represents the `.baz()` in `foo.bar().baz()`,
566 /// `method_chain_args(expr, &["bar", "baz"])` will return a `Vec`
567 /// containing the `Expr`s for
568 /// `.bar()` and `.baz()`
569 pub fn method_chain_args<'a>(expr: &'a Expr<'_>, methods: &[&str]) -> Option<Vec<&'a [Expr<'a>]>> {
570 let mut current = expr;
571 let mut matched = Vec::with_capacity(methods.len());
572 for method_name in methods.iter().rev() {
573 // method chains are stored last -> first
574 if let ExprKind::MethodCall(ref path, _, ref args, _) = current.kind {
575 if path.ident.name.as_str() == *method_name {
576 if args.iter().any(|e| e.span.from_expansion()) {
579 matched.push(&**args); // build up `matched` backwards
580 current = &args[0] // go to parent expression
588 // Reverse `matched` so that it is in the same order as `methods`.
593 /// Returns `true` if the provided `def_id` is an entrypoint to a program.
594 pub fn is_entrypoint_fn(cx: &LateContext<'_>, def_id: DefId) -> bool {
596 .entry_fn(LOCAL_CRATE)
597 .map_or(false, |(entry_fn_def_id, _)| def_id == entry_fn_def_id.to_def_id())
600 /// Returns `true` if the expression is in the program's `#[panic_handler]`.
601 pub fn is_in_panic_handler(cx: &LateContext<'_>, e: &Expr<'_>) -> bool {
602 let parent = cx.tcx.hir().get_parent_item(e.hir_id);
603 let def_id = cx.tcx.hir().local_def_id(parent).to_def_id();
604 Some(def_id) == cx.tcx.lang_items().panic_impl()
607 /// Gets the name of the item the expression is in, if available.
608 pub fn get_item_name(cx: &LateContext<'_>, expr: &Expr<'_>) -> Option<Symbol> {
609 let parent_id = cx.tcx.hir().get_parent_item(expr.hir_id);
610 match cx.tcx.hir().find(parent_id) {
612 Node::Item(Item { ident, .. })
613 | Node::TraitItem(TraitItem { ident, .. })
614 | Node::ImplItem(ImplItem { ident, .. }),
615 ) => Some(ident.name),
620 /// Gets the name of a `Pat`, if any.
621 pub fn get_pat_name(pat: &Pat<'_>) -> Option<Symbol> {
623 PatKind::Binding(.., ref spname, _) => Some(spname.name),
624 PatKind::Path(ref qpath) => single_segment_path(qpath).map(|ps| ps.ident.name),
625 PatKind::Box(ref p) | PatKind::Ref(ref p, _) => get_pat_name(&*p),
630 struct ContainsName {
635 impl<'tcx> Visitor<'tcx> for ContainsName {
636 type Map = Map<'tcx>;
638 fn visit_name(&mut self, _: Span, name: Symbol) {
639 if self.name == name {
643 fn nested_visit_map(&mut self) -> NestedVisitorMap<Self::Map> {
644 NestedVisitorMap::None
648 /// Checks if an `Expr` contains a certain name.
649 pub fn contains_name(name: Symbol, expr: &Expr<'_>) -> bool {
650 let mut cn = ContainsName { name, result: false };
655 /// Returns `true` if `expr` contains a return expression
656 pub fn contains_return(expr: &hir::Expr<'_>) -> bool {
657 struct RetCallFinder {
661 impl<'tcx> hir::intravisit::Visitor<'tcx> for RetCallFinder {
662 type Map = Map<'tcx>;
664 fn visit_expr(&mut self, expr: &'tcx hir::Expr<'_>) {
668 if let hir::ExprKind::Ret(..) = &expr.kind {
671 hir::intravisit::walk_expr(self, expr);
675 fn nested_visit_map(&mut self) -> hir::intravisit::NestedVisitorMap<Self::Map> {
676 hir::intravisit::NestedVisitorMap::None
680 let mut visitor = RetCallFinder { found: false };
681 visitor.visit_expr(expr);
685 struct FindMacroCalls<'a, 'b> {
686 names: &'a [&'b str],
690 impl<'a, 'b, 'tcx> Visitor<'tcx> for FindMacroCalls<'a, 'b> {
691 type Map = Map<'tcx>;
693 fn visit_expr(&mut self, expr: &'tcx Expr<'_>) {
694 if self.names.iter().any(|fun| is_expn_of(expr.span, fun).is_some()) {
695 self.result.push(expr.span);
697 // and check sub-expressions
698 intravisit::walk_expr(self, expr);
701 fn nested_visit_map(&mut self) -> NestedVisitorMap<Self::Map> {
702 NestedVisitorMap::None
706 /// Finds calls of the specified macros in a function body.
707 pub fn find_macro_calls(names: &[&str], body: &Body<'_>) -> Vec<Span> {
708 let mut fmc = FindMacroCalls {
712 fmc.visit_expr(&body.value);
716 /// Converts a span to a code snippet if available, otherwise use default.
718 /// This is useful if you want to provide suggestions for your lint or more generally, if you want
719 /// to convert a given `Span` to a `str`.
723 /// snippet(cx, expr.span, "..")
725 pub fn snippet<'a, T: LintContext>(cx: &T, span: Span, default: &'a str) -> Cow<'a, str> {
726 snippet_opt(cx, span).map_or_else(|| Cow::Borrowed(default), From::from)
729 /// Same as `snippet`, but it adapts the applicability level by following rules:
731 /// - Applicability level `Unspecified` will never be changed.
732 /// - If the span is inside a macro, change the applicability level to `MaybeIncorrect`.
733 /// - If the default value is used and the applicability level is `MachineApplicable`, change it to
734 /// `HasPlaceholders`
735 pub fn snippet_with_applicability<'a, T: LintContext>(
739 applicability: &mut Applicability,
741 if *applicability != Applicability::Unspecified && span.from_expansion() {
742 *applicability = Applicability::MaybeIncorrect;
744 snippet_opt(cx, span).map_or_else(
746 if *applicability == Applicability::MachineApplicable {
747 *applicability = Applicability::HasPlaceholders;
749 Cow::Borrowed(default)
755 /// Same as `snippet`, but should only be used when it's clear that the input span is
756 /// not a macro argument.
757 pub fn snippet_with_macro_callsite<'a, T: LintContext>(cx: &T, span: Span, default: &'a str) -> Cow<'a, str> {
758 snippet(cx, span.source_callsite(), default)
761 /// Converts a span to a code snippet. Returns `None` if not available.
762 pub fn snippet_opt<T: LintContext>(cx: &T, span: Span) -> Option<String> {
763 cx.sess().source_map().span_to_snippet(span).ok()
766 /// Converts a span (from a block) to a code snippet if available, otherwise use default.
768 /// This trims the code of indentation, except for the first line. Use it for blocks or block-like
769 /// things which need to be printed as such.
771 /// The `indent_relative_to` arg can be used, to provide a span, where the indentation of the
772 /// resulting snippet of the given span.
777 /// snippet_block(cx, block.span, "..", None)
778 /// // where, `block` is the block of the if expr
782 /// // will return the snippet
789 /// snippet_block(cx, block.span, "..", Some(if_expr.span))
790 /// // where, `block` is the block of the if expr
794 /// // will return the snippet
797 /// } // aligned with `if`
799 /// Note that the first line of the snippet always has 0 indentation.
800 pub fn snippet_block<'a, T: LintContext>(
804 indent_relative_to: Option<Span>,
806 let snip = snippet(cx, span, default);
807 let indent = indent_relative_to.and_then(|s| indent_of(cx, s));
808 reindent_multiline(snip, true, indent)
811 /// Same as `snippet_block`, but adapts the applicability level by the rules of
812 /// `snippet_with_applicability`.
813 pub fn snippet_block_with_applicability<'a, T: LintContext>(
817 indent_relative_to: Option<Span>,
818 applicability: &mut Applicability,
820 let snip = snippet_with_applicability(cx, span, default, applicability);
821 let indent = indent_relative_to.and_then(|s| indent_of(cx, s));
822 reindent_multiline(snip, true, indent)
825 /// Same as `snippet_with_applicability`, but first walks the span up to the given context. This
826 /// will result in the macro call, rather then the expansion, if the span is from a child context.
827 /// If the span is not from a child context, it will be used directly instead.
829 /// e.g. Given the expression `&vec![]`, getting a snippet from the span for `vec![]` as a HIR node
830 /// would result in `box []`. If given the context of the address of expression, this function will
831 /// correctly get a snippet of `vec![]`.
833 /// This will also return whether or not the snippet is a macro call.
834 pub fn snippet_with_context(
835 cx: &LateContext<'_>,
837 outer: SyntaxContext,
839 applicability: &mut Applicability,
840 ) -> (Cow<'a, str>, bool) {
841 let outer_span = hygiene::walk_chain(span, outer);
842 let (span, is_macro_call) = if outer_span.ctxt() == outer {
843 (outer_span, span.ctxt() != outer)
845 // The span is from a macro argument, and the outer context is the macro using the argument
846 if *applicability != Applicability::Unspecified {
847 *applicability = Applicability::MaybeIncorrect;
849 // TODO: get the argument span.
854 snippet_with_applicability(cx, span, default, applicability),
859 /// Returns a new Span that extends the original Span to the first non-whitespace char of the first
865 /// // will be converted to
869 pub fn first_line_of_span<T: LintContext>(cx: &T, span: Span) -> Span {
870 first_char_in_first_line(cx, span).map_or(span, |first_char_pos| span.with_lo(first_char_pos))
873 fn first_char_in_first_line<T: LintContext>(cx: &T, span: Span) -> Option<BytePos> {
874 let line_span = line_span(cx, span);
875 snippet_opt(cx, line_span).and_then(|snip| {
876 snip.find(|c: char| !c.is_whitespace())
877 .map(|pos| line_span.lo() + BytePos::from_usize(pos))
881 /// Returns the indentation of the line of a span
885 /// // ^^ -- will return 0
887 /// // ^^ -- will return 4
889 pub fn indent_of<T: LintContext>(cx: &T, span: Span) -> Option<usize> {
890 snippet_opt(cx, line_span(cx, span)).and_then(|snip| snip.find(|c: char| !c.is_whitespace()))
893 /// Returns the positon just before rarrow
896 /// fn into(self) -> () {}
898 /// // in case of unformatted code
899 /// fn into2(self)-> () {}
901 /// fn into3(self) -> () {}
904 pub fn position_before_rarrow(s: &str) -> Option<usize> {
905 s.rfind("->").map(|rpos| {
907 let chars: Vec<char> = s.chars().collect();
909 if let Some(c) = chars.get(rpos - 1) {
910 if c.is_whitespace() {
921 /// Extends the span to the beginning of the spans line, incl. whitespaces.
926 /// // will be converted to
928 /// // ^^^^^^^^^^^^^^
930 fn line_span<T: LintContext>(cx: &T, span: Span) -> Span {
931 let span = original_sp(span, DUMMY_SP);
932 let source_map_and_line = cx.sess().source_map().lookup_line(span.lo()).unwrap();
933 let line_no = source_map_and_line.line;
934 let line_start = source_map_and_line.sf.lines[line_no];
935 Span::new(line_start, span.hi(), span.ctxt())
938 /// Like `snippet_block`, but add braces if the expr is not an `ExprKind::Block`.
939 /// Also takes an `Option<String>` which can be put inside the braces.
940 pub fn expr_block<'a, T: LintContext>(
943 option: Option<String>,
945 indent_relative_to: Option<Span>,
947 let code = snippet_block(cx, expr.span, default, indent_relative_to);
948 let string = option.unwrap_or_default();
949 if expr.span.from_expansion() {
950 Cow::Owned(format!("{{ {} }}", snippet_with_macro_callsite(cx, expr.span, default)))
951 } else if let ExprKind::Block(_, _) = expr.kind {
952 Cow::Owned(format!("{}{}", code, string))
953 } else if string.is_empty() {
954 Cow::Owned(format!("{{ {} }}", code))
956 Cow::Owned(format!("{{\n{};\n{}\n}}", code, string))
960 /// Reindent a multiline string with possibility of ignoring the first line.
961 #[allow(clippy::needless_pass_by_value)]
962 pub fn reindent_multiline(s: Cow<'_, str>, ignore_first: bool, indent: Option<usize>) -> Cow<'_, str> {
963 let s_space = reindent_multiline_inner(&s, ignore_first, indent, ' ');
964 let s_tab = reindent_multiline_inner(&s_space, ignore_first, indent, '\t');
965 reindent_multiline_inner(&s_tab, ignore_first, indent, ' ').into()
968 fn reindent_multiline_inner(s: &str, ignore_first: bool, indent: Option<usize>, ch: char) -> String {
971 .skip(ignore_first as usize)
976 // ignore empty lines
977 Some(l.char_indices().find(|&(_, x)| x != ch).unwrap_or((l.len(), ch)).0)
982 let indent = indent.unwrap_or(0);
986 if (ignore_first && i == 0) || l.is_empty() {
988 } else if x > indent {
989 l.split_at(x - indent).1.to_owned()
991 " ".repeat(indent - x) + l
994 .collect::<Vec<String>>()
998 /// Gets the span of the node, if there is one.
999 pub fn get_node_span(node: Node<'_>) -> Option<Span> {
1001 Node::Param(Param { span, .. })
1002 | Node::Item(Item { span, .. })
1003 | Node::ForeignItem(ForeignItem { span, .. })
1004 | Node::TraitItem(TraitItem { span, .. })
1005 | Node::ImplItem(ImplItem { span, .. })
1006 | Node::Variant(Variant { span, .. })
1007 | Node::Field(StructField { span, .. })
1008 | Node::Expr(Expr { span, .. })
1009 | Node::Stmt(Stmt { span, .. })
1010 | Node::PathSegment(PathSegment {
1011 ident: Ident { span, .. },
1014 | Node::Ty(hir::Ty { span, .. })
1015 | Node::TraitRef(TraitRef {
1016 path: Path { span, .. },
1019 | Node::Binding(Pat { span, .. })
1020 | Node::Pat(Pat { span, .. })
1021 | Node::Arm(Arm { span, .. })
1022 | Node::Block(Block { span, .. })
1023 | Node::Local(Local { span, .. })
1024 | Node::MacroDef(MacroDef { span, .. })
1025 | Node::Lifetime(Lifetime { span, .. })
1026 | Node::GenericParam(GenericParam { span, .. })
1027 | Node::Visibility(Visibility { span, .. })
1028 | Node::Crate(CrateItem { span, .. }) => Some(*span),
1029 Node::Ctor(_) | Node::AnonConst(_) => None,
1033 /// Gets the parent node, if any.
1034 pub fn get_parent_node(tcx: TyCtxt<'_>, id: HirId) -> Option<Node<'_>> {
1035 tcx.hir().parent_iter(id).next().map(|(_, node)| node)
1038 /// Gets the parent expression, if any –- this is useful to constrain a lint.
1039 pub fn get_parent_expr<'tcx>(cx: &LateContext<'tcx>, e: &Expr<'_>) -> Option<&'tcx Expr<'tcx>> {
1040 match get_parent_node(cx.tcx, e.hir_id) {
1041 Some(Node::Expr(parent)) => Some(parent),
1046 pub fn get_enclosing_block<'tcx>(cx: &LateContext<'tcx>, hir_id: HirId) -> Option<&'tcx Block<'tcx>> {
1047 let map = &cx.tcx.hir();
1048 let enclosing_node = map
1049 .get_enclosing_scope(hir_id)
1050 .and_then(|enclosing_id| map.find(enclosing_id));
1051 enclosing_node.and_then(|node| match node {
1052 Node::Block(block) => Some(block),
1054 kind: ItemKind::Fn(_, _, eid),
1057 | Node::ImplItem(&ImplItem {
1058 kind: ImplItemKind::Fn(_, eid),
1060 }) => match cx.tcx.hir().body(eid).value.kind {
1061 ExprKind::Block(ref block, _) => Some(block),
1068 /// Gets the parent node if it's an impl block.
1069 pub fn get_parent_as_impl(tcx: TyCtxt<'_>, id: HirId) -> Option<&Impl<'_>> {
1070 let map = tcx.hir();
1071 match map.parent_iter(id).next() {
1075 kind: ItemKind::Impl(imp),
1083 /// Checks whether the given expression is a constant integer of the given value.
1084 /// unlike `is_integer_literal`, this version does const folding
1085 pub fn is_integer_const(cx: &LateContext<'_>, e: &Expr<'_>, value: u128) -> bool {
1086 if is_integer_literal(e, value) {
1089 let map = cx.tcx.hir();
1090 let parent_item = map.get_parent_item(e.hir_id);
1091 if let Some((Constant::Int(v), _)) = map
1092 .maybe_body_owned_by(parent_item)
1093 .and_then(|body_id| constant(cx, cx.tcx.typeck_body(body_id), e))
1101 /// Checks whether the given expression is a constant literal of the given value.
1102 pub fn is_integer_literal(expr: &Expr<'_>, value: u128) -> bool {
1103 // FIXME: use constant folding
1104 if let ExprKind::Lit(ref spanned) = expr.kind {
1105 if let LitKind::Int(v, _) = spanned.node {
1112 /// Returns `true` if the given `Expr` has been coerced before.
1114 /// Examples of coercions can be found in the Nomicon at
1115 /// <https://doc.rust-lang.org/nomicon/coercions.html>.
1117 /// See `rustc_middle::ty::adjustment::Adjustment` and `rustc_typeck::check::coercion` for more
1118 /// information on adjustments and coercions.
1119 pub fn is_adjusted(cx: &LateContext<'_>, e: &Expr<'_>) -> bool {
1120 cx.typeck_results().adjustments().get(e.hir_id).is_some()
1123 /// Returns the pre-expansion span if is this comes from an expansion of the
1125 /// See also `is_direct_expn_of`.
1127 pub fn is_expn_of(mut span: Span, name: &str) -> Option<Span> {
1129 if span.from_expansion() {
1130 let data = span.ctxt().outer_expn_data();
1131 let new_span = data.call_site;
1133 if let ExpnKind::Macro(MacroKind::Bang, mac_name) = data.kind {
1134 if mac_name.as_str() == name {
1135 return Some(new_span);
1146 /// Returns the pre-expansion span if the span directly comes from an expansion
1147 /// of the macro `name`.
1148 /// The difference with `is_expn_of` is that in
1152 /// `42` is considered expanded from `foo!` and `bar!` by `is_expn_of` but only
1154 /// `is_direct_expn_of`.
1156 pub fn is_direct_expn_of(span: Span, name: &str) -> Option<Span> {
1157 if span.from_expansion() {
1158 let data = span.ctxt().outer_expn_data();
1159 let new_span = data.call_site;
1161 if let ExpnKind::Macro(MacroKind::Bang, mac_name) = data.kind {
1162 if mac_name.as_str() == name {
1163 return Some(new_span);
1171 /// Convenience function to get the return type of a function.
1172 pub fn return_ty<'tcx>(cx: &LateContext<'tcx>, fn_item: hir::HirId) -> Ty<'tcx> {
1173 let fn_def_id = cx.tcx.hir().local_def_id(fn_item);
1174 let ret_ty = cx.tcx.fn_sig(fn_def_id).output();
1175 cx.tcx.erase_late_bound_regions(ret_ty)
1178 /// Checks if an expression is constructing a tuple-like enum variant or struct
1179 pub fn is_ctor_or_promotable_const_function(cx: &LateContext<'_>, expr: &Expr<'_>) -> bool {
1180 if let ExprKind::Call(ref fun, _) = expr.kind {
1181 if let ExprKind::Path(ref qp) = fun.kind {
1182 let res = cx.qpath_res(qp, fun.hir_id);
1184 def::Res::Def(DefKind::Variant | DefKind::Ctor(..), ..) => true,
1185 def::Res::Def(_, def_id) => cx.tcx.is_promotable_const_fn(def_id),
1193 /// Returns `true` if a pattern is refutable.
1194 // TODO: should be implemented using rustc/mir_build/thir machinery
1195 pub fn is_refutable(cx: &LateContext<'_>, pat: &Pat<'_>) -> bool {
1196 fn is_enum_variant(cx: &LateContext<'_>, qpath: &QPath<'_>, id: HirId) -> bool {
1198 cx.qpath_res(qpath, id),
1199 def::Res::Def(DefKind::Variant, ..) | Res::Def(DefKind::Ctor(def::CtorOf::Variant, _), _)
1203 fn are_refutable<'a, I: Iterator<Item = &'a Pat<'a>>>(cx: &LateContext<'_>, mut i: I) -> bool {
1204 i.any(|pat| is_refutable(cx, pat))
1208 PatKind::Wild => false,
1209 PatKind::Binding(_, _, _, pat) => pat.map_or(false, |pat| is_refutable(cx, pat)),
1210 PatKind::Box(ref pat) | PatKind::Ref(ref pat, _) => is_refutable(cx, pat),
1211 PatKind::Lit(..) | PatKind::Range(..) => true,
1212 PatKind::Path(ref qpath) => is_enum_variant(cx, qpath, pat.hir_id),
1213 PatKind::Or(ref pats) => {
1214 // TODO: should be the honest check, that pats is exhaustive set
1215 are_refutable(cx, pats.iter().map(|pat| &**pat))
1217 PatKind::Tuple(ref pats, _) => are_refutable(cx, pats.iter().map(|pat| &**pat)),
1218 PatKind::Struct(ref qpath, ref fields, _) => {
1219 is_enum_variant(cx, qpath, pat.hir_id) || are_refutable(cx, fields.iter().map(|field| &*field.pat))
1221 PatKind::TupleStruct(ref qpath, ref pats, _) => {
1222 is_enum_variant(cx, qpath, pat.hir_id) || are_refutable(cx, pats.iter().map(|pat| &**pat))
1224 PatKind::Slice(ref head, ref middle, ref tail) => {
1225 match &cx.typeck_results().node_type(pat.hir_id).kind() {
1226 rustc_ty::Slice(..) => {
1227 // [..] is the only irrefutable slice pattern.
1228 !head.is_empty() || middle.is_none() || !tail.is_empty()
1230 rustc_ty::Array(..) => {
1231 are_refutable(cx, head.iter().chain(middle).chain(tail.iter()).map(|pat| &**pat))
1242 /// Checks for the `#[automatically_derived]` attribute all `#[derive]`d
1243 /// implementations have.
1244 pub fn is_automatically_derived(attrs: &[ast::Attribute]) -> bool {
1245 attrs.iter().any(|attr| attr.has_name(sym::automatically_derived))
1248 /// Remove blocks around an expression.
1250 /// Ie. `x`, `{ x }` and `{{{{ x }}}}` all give `x`. `{ x; y }` and `{}` return
1252 pub fn remove_blocks<'tcx>(mut expr: &'tcx Expr<'tcx>) -> &'tcx Expr<'tcx> {
1253 while let ExprKind::Block(ref block, ..) = expr.kind {
1254 match (block.stmts.is_empty(), block.expr.as_ref()) {
1255 (true, Some(e)) => expr = e,
1262 pub fn is_self(slf: &Param<'_>) -> bool {
1263 if let PatKind::Binding(.., name, _) = slf.pat.kind {
1264 name.name == kw::SelfLower
1270 pub fn is_self_ty(slf: &hir::Ty<'_>) -> bool {
1272 if let TyKind::Path(QPath::Resolved(None, ref path)) = slf.kind;
1273 if let Res::SelfTy(..) = path.res;
1281 pub fn iter_input_pats<'tcx>(decl: &FnDecl<'_>, body: &'tcx Body<'_>) -> impl Iterator<Item = &'tcx Param<'tcx>> {
1282 (0..decl.inputs.len()).map(move |i| &body.params[i])
1285 /// Checks if a given expression is a match expression expanded from the `?`
1286 /// operator or the `try` macro.
1287 pub fn is_try<'tcx>(expr: &'tcx Expr<'tcx>) -> Option<&'tcx Expr<'tcx>> {
1288 fn is_ok(arm: &Arm<'_>) -> bool {
1290 if let PatKind::TupleStruct(ref path, ref pat, None) = arm.pat.kind;
1291 if match_qpath(path, &paths::RESULT_OK[1..]);
1292 if let PatKind::Binding(_, hir_id, _, None) = pat[0].kind;
1293 if path_to_local_id(arm.body, hir_id);
1301 fn is_err(arm: &Arm<'_>) -> bool {
1302 if let PatKind::TupleStruct(ref path, _, _) = arm.pat.kind {
1303 match_qpath(path, &paths::RESULT_ERR[1..])
1309 if let ExprKind::Match(_, ref arms, ref source) = expr.kind {
1310 // desugared from a `?` operator
1311 if let MatchSource::TryDesugar = *source {
1317 if arms[0].guard.is_none();
1318 if arms[1].guard.is_none();
1319 if (is_ok(&arms[0]) && is_err(&arms[1])) ||
1320 (is_ok(&arms[1]) && is_err(&arms[0]));
1330 /// Returns `true` if the lint is allowed in the current context
1332 /// Useful for skipping long running code when it's unnecessary
1333 pub fn is_allowed(cx: &LateContext<'_>, lint: &'static Lint, id: HirId) -> bool {
1334 cx.tcx.lint_level_at_node(lint, id).0 == Level::Allow
1337 pub fn strip_pat_refs<'hir>(mut pat: &'hir Pat<'hir>) -> &'hir Pat<'hir> {
1338 while let PatKind::Ref(subpat, _) = pat.kind {
1344 pub fn int_bits(tcx: TyCtxt<'_>, ity: rustc_ty::IntTy) -> u64 {
1345 Integer::from_int_ty(&tcx, ity).size().bits()
1348 #[allow(clippy::cast_possible_wrap)]
1349 /// Turn a constant int byte representation into an i128
1350 pub fn sext(tcx: TyCtxt<'_>, u: u128, ity: rustc_ty::IntTy) -> i128 {
1351 let amt = 128 - int_bits(tcx, ity);
1352 ((u as i128) << amt) >> amt
1355 #[allow(clippy::cast_sign_loss)]
1356 /// clip unused bytes
1357 pub fn unsext(tcx: TyCtxt<'_>, u: i128, ity: rustc_ty::IntTy) -> u128 {
1358 let amt = 128 - int_bits(tcx, ity);
1359 ((u as u128) << amt) >> amt
1362 /// clip unused bytes
1363 pub fn clip(tcx: TyCtxt<'_>, u: u128, ity: rustc_ty::UintTy) -> u128 {
1364 let bits = Integer::from_uint_ty(&tcx, ity).size().bits();
1365 let amt = 128 - bits;
1369 /// Removes block comments from the given `Vec` of lines.
1374 /// without_block_comments(vec!["/*", "foo", "*/"]);
1377 /// without_block_comments(vec!["bar", "/*", "foo", "*/"]);
1378 /// // => vec!["bar"]
1380 pub fn without_block_comments(lines: Vec<&str>) -> Vec<&str> {
1381 let mut without = vec![];
1383 let mut nest_level = 0;
1386 if line.contains("/*") {
1389 } else if line.contains("*/") {
1394 if nest_level == 0 {
1402 pub fn any_parent_is_automatically_derived(tcx: TyCtxt<'_>, node: HirId) -> bool {
1403 let map = &tcx.hir();
1404 let mut prev_enclosing_node = None;
1405 let mut enclosing_node = node;
1406 while Some(enclosing_node) != prev_enclosing_node {
1407 if is_automatically_derived(map.attrs(enclosing_node)) {
1410 prev_enclosing_node = Some(enclosing_node);
1411 enclosing_node = map.get_parent_item(enclosing_node);
1416 /// Matches a function call with the given path and returns the arguments.
1421 /// if let Some(args) = match_function_call(cx, cmp_max_call, &paths::CMP_MAX);
1423 pub fn match_function_call<'tcx>(
1424 cx: &LateContext<'tcx>,
1425 expr: &'tcx Expr<'_>,
1427 ) -> Option<&'tcx [Expr<'tcx>]> {
1429 if let ExprKind::Call(ref fun, ref args) = expr.kind;
1430 if let ExprKind::Path(ref qpath) = fun.kind;
1431 if let Some(fun_def_id) = cx.qpath_res(qpath, fun.hir_id).opt_def_id();
1432 if match_def_path(cx, fun_def_id, path);
1440 pub fn match_def_path<'tcx>(cx: &LateContext<'tcx>, did: DefId, syms: &[&str]) -> bool {
1441 // We have to convert `syms` to `&[Symbol]` here because rustc's `match_def_path`
1442 // accepts only that. We should probably move to Symbols in Clippy as well.
1443 let syms = syms.iter().map(|p| Symbol::intern(p)).collect::<Vec<Symbol>>();
1444 cx.match_def_path(did, &syms)
1447 pub fn match_panic_call<'tcx>(cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) -> Option<&'tcx [Expr<'tcx>]> {
1448 match_function_call(cx, expr, &paths::BEGIN_PANIC)
1449 .or_else(|| match_function_call(cx, expr, &paths::BEGIN_PANIC_FMT))
1450 .or_else(|| match_function_call(cx, expr, &paths::PANIC_ANY))
1451 .or_else(|| match_function_call(cx, expr, &paths::PANICKING_PANIC))
1452 .or_else(|| match_function_call(cx, expr, &paths::PANICKING_PANIC_FMT))
1453 .or_else(|| match_function_call(cx, expr, &paths::PANICKING_PANIC_STR))
1456 pub fn match_panic_def_id(cx: &LateContext<'_>, did: DefId) -> bool {
1457 match_def_path(cx, did, &paths::BEGIN_PANIC)
1458 || match_def_path(cx, did, &paths::BEGIN_PANIC_FMT)
1459 || match_def_path(cx, did, &paths::PANIC_ANY)
1460 || match_def_path(cx, did, &paths::PANICKING_PANIC)
1461 || match_def_path(cx, did, &paths::PANICKING_PANIC_FMT)
1462 || match_def_path(cx, did, &paths::PANICKING_PANIC_STR)
1465 /// Returns the list of condition expressions and the list of blocks in a
1466 /// sequence of `if/else`.
1467 /// E.g., this returns `([a, b], [c, d, e])` for the expression
1468 /// `if a { c } else if b { d } else { e }`.
1469 pub fn if_sequence<'tcx>(
1470 mut expr: &'tcx Expr<'tcx>,
1471 ) -> (SmallVec<[&'tcx Expr<'tcx>; 1]>, SmallVec<[&'tcx Block<'tcx>; 1]>) {
1472 let mut conds = SmallVec::new();
1473 let mut blocks: SmallVec<[&Block<'_>; 1]> = SmallVec::new();
1475 while let ExprKind::If(ref cond, ref then_expr, ref else_expr) = expr.kind {
1476 conds.push(&**cond);
1477 if let ExprKind::Block(ref block, _) = then_expr.kind {
1480 panic!("ExprKind::If node is not an ExprKind::Block");
1483 if let Some(ref else_expr) = *else_expr {
1490 // final `else {..}`
1491 if !blocks.is_empty() {
1492 if let ExprKind::Block(ref block, _) = expr.kind {
1493 blocks.push(&**block);
1500 pub fn parent_node_is_if_expr(expr: &Expr<'_>, cx: &LateContext<'_>) -> bool {
1501 let map = cx.tcx.hir();
1502 let parent_id = map.get_parent_node(expr.hir_id);
1503 let parent_node = map.get(parent_id);
1507 kind: ExprKind::If(_, _, _),
1513 // Finds the attribute with the given name, if any
1514 pub fn attr_by_name<'a>(attrs: &'a [Attribute], name: &'_ str) -> Option<&'a Attribute> {
1517 .find(|attr| attr.ident().map_or(false, |ident| ident.as_str() == name))
1520 // Finds the `#[must_use]` attribute, if any
1521 pub fn must_use_attr(attrs: &[Attribute]) -> Option<&Attribute> {
1522 attr_by_name(attrs, "must_use")
1525 // check if expr is calling method or function with #[must_use] attribute
1526 pub fn is_must_use_func_call(cx: &LateContext<'_>, expr: &Expr<'_>) -> bool {
1527 let did = match expr.kind {
1528 ExprKind::Call(ref path, _) => if_chain! {
1529 if let ExprKind::Path(ref qpath) = path.kind;
1530 if let def::Res::Def(_, did) = cx.qpath_res(qpath, path.hir_id);
1537 ExprKind::MethodCall(_, _, _, _) => cx.typeck_results().type_dependent_def_id(expr.hir_id),
1541 did.map_or(false, |did| must_use_attr(&cx.tcx.get_attrs(did)).is_some())
1544 pub fn is_no_std_crate(cx: &LateContext<'_>) -> bool {
1545 cx.tcx.hir().attrs(hir::CRATE_HIR_ID).iter().any(|attr| {
1546 if let ast::AttrKind::Normal(ref attr, _) = attr.kind {
1547 attr.path == sym::no_std
1554 /// Check if parent of a hir node is a trait implementation block.
1555 /// For example, `f` in
1557 /// impl Trait for S {
1561 pub fn is_trait_impl_item(cx: &LateContext<'_>, hir_id: HirId) -> bool {
1562 if let Some(Node::Item(item)) = cx.tcx.hir().find(cx.tcx.hir().get_parent_node(hir_id)) {
1563 matches!(item.kind, ItemKind::Impl(hir::Impl { of_trait: Some(_), .. }))
1569 /// Check if it's even possible to satisfy the `where` clause for the item.
1571 /// `trivial_bounds` feature allows functions with unsatisfiable bounds, for example:
1574 /// fn foo() where i32: Iterator {
1575 /// for _ in 2i32 {}
1578 pub fn fn_has_unsatisfiable_preds(cx: &LateContext<'_>, did: DefId) -> bool {
1579 use rustc_trait_selection::traits;
1585 .filter_map(|(p, _)| if p.is_global() { Some(*p) } else { None });
1586 traits::impossible_predicates(
1588 traits::elaborate_predicates(cx.tcx, predicates)
1589 .map(|o| o.predicate)
1590 .collect::<Vec<_>>(),
1594 /// Returns the `DefId` of the callee if the given expression is a function or method call.
1595 pub fn fn_def_id(cx: &LateContext<'_>, expr: &Expr<'_>) -> Option<DefId> {
1597 ExprKind::MethodCall(..) => cx.typeck_results().type_dependent_def_id(expr.hir_id),
1600 kind: ExprKind::Path(qpath),
1601 hir_id: path_hir_id,
1605 ) => cx.typeck_results().qpath_res(qpath, *path_hir_id).opt_def_id(),
1610 pub fn run_lints(cx: &LateContext<'_>, lints: &[&'static Lint], id: HirId) -> bool {
1611 lints.iter().any(|lint| {
1613 cx.tcx.lint_level_at_node(lint, id),
1614 (Level::Forbid | Level::Deny | Level::Warn, _)
1619 /// Returns Option<String> where String is a textual representation of the type encapsulated in the
1620 /// slice iff the given expression is a slice of primitives (as defined in the
1621 /// `is_recursively_primitive_type` function) and None otherwise.
1622 pub fn is_slice_of_primitives(cx: &LateContext<'_>, expr: &Expr<'_>) -> Option<String> {
1623 let expr_type = cx.typeck_results().expr_ty_adjusted(expr);
1624 let expr_kind = expr_type.kind();
1625 let is_primitive = match expr_kind {
1626 rustc_ty::Slice(element_type) => is_recursively_primitive_type(element_type),
1627 rustc_ty::Ref(_, inner_ty, _) if matches!(inner_ty.kind(), &rustc_ty::Slice(_)) => {
1628 if let rustc_ty::Slice(element_type) = inner_ty.kind() {
1629 is_recursively_primitive_type(element_type)
1638 // if we have wrappers like Array, Slice or Tuple, print these
1639 // and get the type enclosed in the slice ref
1640 match expr_type.peel_refs().walk().nth(1).unwrap().expect_ty().kind() {
1641 rustc_ty::Slice(..) => return Some("slice".into()),
1642 rustc_ty::Array(..) => return Some("array".into()),
1643 rustc_ty::Tuple(..) => return Some("tuple".into()),
1645 // is_recursively_primitive_type() should have taken care
1646 // of the rest and we can rely on the type that is found
1647 let refs_peeled = expr_type.peel_refs();
1648 return Some(refs_peeled.walk().last().unwrap().to_string());
1655 /// returns list of all pairs (a, b) from `exprs` such that `eq(a, b)`
1656 /// `hash` must be comformed with `eq`
1657 pub fn search_same<T, Hash, Eq>(exprs: &[T], hash: Hash, eq: Eq) -> Vec<(&T, &T)>
1659 Hash: Fn(&T) -> u64,
1660 Eq: Fn(&T, &T) -> bool,
1662 if exprs.len() == 2 && eq(&exprs[0], &exprs[1]) {
1663 return vec![(&exprs[0], &exprs[1])];
1666 let mut match_expr_list: Vec<(&T, &T)> = Vec::new();
1668 let mut map: FxHashMap<_, Vec<&_>> =
1669 FxHashMap::with_capacity_and_hasher(exprs.len(), BuildHasherDefault::default());
1672 match map.entry(hash(expr)) {
1673 Entry::Occupied(mut o) => {
1676 match_expr_list.push((o, expr));
1679 o.get_mut().push(expr);
1681 Entry::Vacant(v) => {
1682 v.insert(vec![expr]);
1690 /// Peels off all references on the pattern. Returns the underlying pattern and the number of
1691 /// references removed.
1692 pub fn peel_hir_pat_refs(pat: &'a Pat<'a>) -> (&'a Pat<'a>, usize) {
1693 fn peel(pat: &'a Pat<'a>, count: usize) -> (&'a Pat<'a>, usize) {
1694 if let PatKind::Ref(pat, _) = pat.kind {
1695 peel(pat, count + 1)
1703 /// Peels off up to the given number of references on the expression. Returns the underlying
1704 /// expression and the number of references removed.
1705 pub fn peel_n_hir_expr_refs(expr: &'a Expr<'a>, count: usize) -> (&'a Expr<'a>, usize) {
1706 fn f(expr: &'a Expr<'a>, count: usize, target: usize) -> (&'a Expr<'a>, usize) {
1708 ExprKind::AddrOf(_, _, expr) if count != target => f(expr, count + 1, target),
1715 /// Peels off all references on the expression. Returns the underlying expression and the number of
1716 /// references removed.
1717 pub fn peel_hir_expr_refs(expr: &'a Expr<'a>) -> (&'a Expr<'a>, usize) {
1718 fn f(expr: &'a Expr<'a>, count: usize) -> (&'a Expr<'a>, usize) {
1720 ExprKind::AddrOf(BorrowKind::Ref, _, expr) => f(expr, count + 1),
1728 macro_rules! unwrap_cargo_metadata {
1729 ($cx: ident, $lint: ident, $deps: expr) => {{
1730 let mut command = cargo_metadata::MetadataCommand::new();
1735 match command.exec() {
1736 Ok(metadata) => metadata,
1738 span_lint($cx, $lint, DUMMY_SP, &format!("could not read cargo metadata: {}", err));
1745 pub fn is_hir_ty_cfg_dependant(cx: &LateContext<'_>, ty: &hir::Ty<'_>) -> bool {
1747 if let TyKind::Path(QPath::Resolved(_, path)) = ty.kind;
1748 if let Res::Def(_, def_id) = path.res;
1750 cx.tcx.has_attr(def_id, sym::cfg) || cx.tcx.has_attr(def_id, sym::cfg_attr)
1757 /// Check if the resolution of a given path is an `Ok` variant of `Result`.
1758 pub fn is_ok_ctor(cx: &LateContext<'_>, res: Res) -> bool {
1759 if let Some(ok_id) = cx.tcx.lang_items().result_ok_variant() {
1760 if let Res::Def(DefKind::Ctor(CtorOf::Variant, CtorKind::Fn), id) = res {
1761 if let Some(variant_id) = cx.tcx.parent(id) {
1762 return variant_id == ok_id;
1769 /// Check if the resolution of a given path is a `Some` variant of `Option`.
1770 pub fn is_some_ctor(cx: &LateContext<'_>, res: Res) -> bool {
1771 if let Some(some_id) = cx.tcx.lang_items().option_some_variant() {
1772 if let Res::Def(DefKind::Ctor(CtorOf::Variant, CtorKind::Fn), id) = res {
1773 if let Some(variant_id) = cx.tcx.parent(id) {
1774 return variant_id == some_id;
1783 use super::{reindent_multiline, without_block_comments};
1786 fn test_reindent_multiline_single_line() {
1787 assert_eq!("", reindent_multiline("".into(), false, None));
1788 assert_eq!("...", reindent_multiline("...".into(), false, None));
1789 assert_eq!("...", reindent_multiline(" ...".into(), false, None));
1790 assert_eq!("...", reindent_multiline("\t...".into(), false, None));
1791 assert_eq!("...", reindent_multiline("\t\t...".into(), false, None));
1796 fn test_reindent_multiline_block() {
1802 }", reindent_multiline(" if x {
1806 }".into(), false, None));
1812 }", reindent_multiline(" if x {
1816 }".into(), false, None));
1821 fn test_reindent_multiline_empty_line() {
1828 }", reindent_multiline(" if x {
1833 }".into(), false, None));
1838 fn test_reindent_multiline_lines_deeper() {
1844 }", reindent_multiline("\
1849 }".into(), true, Some(8)));
1853 fn test_without_block_comments_lines_without_block_comments() {
1854 let result = without_block_comments(vec!["/*", "", "*/"]);
1855 println!("result: {:?}", result);
1856 assert!(result.is_empty());
1858 let result = without_block_comments(vec!["", "/*", "", "*/", "#[crate_type = \"lib\"]", "/*", "", "*/", ""]);
1859 assert_eq!(result, vec!["", "#[crate_type = \"lib\"]", ""]);
1861 let result = without_block_comments(vec!["/* rust", "", "*/"]);
1862 assert!(result.is_empty());
1864 let result = without_block_comments(vec!["/* one-line comment */"]);
1865 assert!(result.is_empty());
1867 let result = without_block_comments(vec!["/* nested", "/* multi-line", "comment", "*/", "test", "*/"]);
1868 assert!(result.is_empty());
1870 let result = without_block_comments(vec!["/* nested /* inline /* comment */ test */ */"]);
1871 assert!(result.is_empty());
1873 let result = without_block_comments(vec!["foo", "bar", "baz"]);
1874 assert_eq!(result, vec!["foo", "bar", "baz"]);