11 pub mod internal_lints;
16 pub use self::attrs::*;
17 pub use self::diagnostics::*;
18 pub use self::hir_utils::{SpanlessEq, SpanlessHash};
23 use if_chain::if_chain;
26 use rustc::hir::def::Def;
27 use rustc::hir::def_id::{DefId, CRATE_DEF_INDEX, LOCAL_CRATE};
28 use rustc::hir::intravisit::{NestedVisitorMap, Visitor};
31 use rustc::lint::{LateContext, Level, Lint, LintContext};
35 layout::{self, IntegerExt},
39 use rustc_data_structures::sync::Lrc;
40 use rustc_errors::Applicability;
41 use syntax::ast::{self, LitKind};
43 use syntax::source_map::{Span, DUMMY_SP};
45 use syntax::symbol::{keywords, Symbol};
47 use crate::reexport::*;
49 /// Returns `true` if the two spans come from differing expansions (i.e., one is
50 /// from a macro and one isn't).
51 pub fn differing_macro_contexts(lhs: Span, rhs: Span) -> bool {
52 rhs.ctxt() != lhs.ctxt()
55 /// Returns `true` if the given `NodeId` is inside a constant context
60 /// if in_constant(cx, expr.id) {
64 pub fn in_constant(cx: &LateContext<'_, '_>, id: HirId) -> bool {
65 let parent_id = cx.tcx.hir().get_parent_item(id);
66 match cx.tcx.hir().get_by_hir_id(parent_id) {
68 node: ItemKind::Const(..),
71 | Node::TraitItem(&TraitItem {
72 node: TraitItemKind::Const(..),
75 | Node::ImplItem(&ImplItem {
76 node: ImplItemKind::Const(..),
81 node: ItemKind::Static(..),
85 node: ItemKind::Fn(_, header, ..),
87 }) => header.constness == Constness::Const,
92 /// Returns `true` if this `expn_info` was expanded by any macro.
93 pub fn in_macro(span: Span) -> bool {
94 span.ctxt().outer().expn_info().is_some()
97 /// Used to store the absolute path to a type.
99 /// See `match_def_path` for usage.
101 pub struct AbsolutePathBuffer {
102 pub names: Vec<symbol::LocalInternedString>,
105 impl ty::item_path::ItemPathBuffer for AbsolutePathBuffer {
106 fn root_mode(&self) -> &ty::item_path::RootMode {
107 const ABSOLUTE: &ty::item_path::RootMode = &ty::item_path::RootMode::Absolute;
111 fn push(&mut self, text: &str) {
112 self.names.push(symbol::Symbol::intern(text).as_str());
116 /// Checks if a `DefId`'s path matches the given absolute type path usage.
120 /// match_def_path(cx.tcx, id, &["core", "option", "Option"])
123 /// See also the `paths` module.
124 pub fn match_def_path(tcx: TyCtxt<'_, '_, '_>, def_id: DefId, path: &[&str]) -> bool {
125 let mut apb = AbsolutePathBuffer { names: vec![] };
127 tcx.push_item_path(&mut apb, def_id, false);
129 apb.names.len() == path.len() && apb.names.into_iter().zip(path.iter()).all(|(a, &b)| *a == *b)
132 /// Gets the absolute path of `def_id` as a vector of `&str`.
136 /// let def_path = get_def_path(tcx, def_id);
137 /// if let &["core", "option", "Option"] = &def_path[..] {
138 /// // The given `def_id` is that of an `Option` type
141 pub fn get_def_path(tcx: TyCtxt<'_, '_, '_>, def_id: DefId) -> Vec<&'static str> {
142 let mut apb = AbsolutePathBuffer { names: vec![] };
143 tcx.push_item_path(&mut apb, def_id, false);
146 .map(syntax_pos::symbol::LocalInternedString::get)
150 /// Checks if type is struct, enum or union type with given def path.
151 pub fn match_type(cx: &LateContext<'_, '_>, ty: Ty<'_>, path: &[&str]) -> bool {
153 ty::Adt(adt, _) => match_def_path(cx.tcx, adt.did, path),
158 /// Checks if the method call given in `expr` belongs to given trait.
159 pub fn match_trait_method(cx: &LateContext<'_, '_>, expr: &Expr, path: &[&str]) -> bool {
160 let method_call = cx.tables.type_dependent_defs()[expr.hir_id];
161 let trt_id = cx.tcx.trait_of_item(method_call.def_id());
162 if let Some(trt_id) = trt_id {
163 match_def_path(cx.tcx, trt_id, path)
169 /// Checks if an expression references a variable of the given name.
170 pub fn match_var(expr: &Expr, var: Name) -> bool {
171 if let ExprKind::Path(QPath::Resolved(None, ref path)) = expr.node {
172 if path.segments.len() == 1 && path.segments[0].ident.name == var {
179 pub fn last_path_segment(path: &QPath) -> &PathSegment {
181 QPath::Resolved(_, ref path) => path.segments.last().expect("A path must have at least one segment"),
182 QPath::TypeRelative(_, ref seg) => seg,
186 pub fn single_segment_path(path: &QPath) -> Option<&PathSegment> {
188 QPath::Resolved(_, ref path) if path.segments.len() == 1 => Some(&path.segments[0]),
189 QPath::Resolved(..) => None,
190 QPath::TypeRelative(_, ref seg) => Some(seg),
194 /// Matches a `QPath` against a slice of segment string literals.
196 /// There is also `match_path` if you are dealing with a `rustc::hir::Path` instead of a
197 /// `rustc::hir::QPath`.
201 /// match_qpath(path, &["std", "rt", "begin_unwind"])
203 pub fn match_qpath(path: &QPath, segments: &[&str]) -> bool {
205 QPath::Resolved(_, ref path) => match_path(path, segments),
206 QPath::TypeRelative(ref ty, ref segment) => match ty.node {
207 TyKind::Path(ref inner_path) => {
209 && match_qpath(inner_path, &segments[..(segments.len() - 1)])
210 && segment.ident.name == segments[segments.len() - 1]
217 /// Matches a `Path` against a slice of segment string literals.
219 /// There is also `match_qpath` if you are dealing with a `rustc::hir::QPath` instead of a
220 /// `rustc::hir::Path`.
225 /// if match_path(&trait_ref.path, &paths::HASH) {
226 /// // This is the `std::hash::Hash` trait.
229 /// if match_path(ty_path, &["rustc", "lint", "Lint"]) {
230 /// // This is a `rustc::lint::Lint`.
233 pub fn match_path(path: &Path, segments: &[&str]) -> bool {
237 .zip(segments.iter().rev())
238 .all(|(a, b)| a.ident.name == *b)
241 /// Matches a `Path` against a slice of segment string literals, e.g.
245 /// match_qpath(path, &["std", "rt", "begin_unwind"])
247 pub fn match_path_ast(path: &ast::Path, segments: &[&str]) -> bool {
251 .zip(segments.iter().rev())
252 .all(|(a, b)| a.ident.name == *b)
255 /// Gets the definition associated to a path.
256 pub fn path_to_def(cx: &LateContext<'_, '_>, path: &[&str]) -> Option<def::Def> {
257 let crates = cx.tcx.crates();
258 let krate = crates.iter().find(|&&krate| cx.tcx.crate_name(krate) == path[0]);
259 if let Some(krate) = krate {
262 index: CRATE_DEF_INDEX,
264 let mut items = cx.tcx.item_children(krate);
265 let mut path_it = path.iter().skip(1).peekable();
268 let segment = match path_it.next() {
269 Some(segment) => segment,
273 for item in mem::replace(&mut items, Lrc::new(vec![])).iter() {
274 if item.ident.name == *segment {
275 if path_it.peek().is_none() {
276 return Some(item.def);
279 items = cx.tcx.item_children(item.def.def_id());
289 /// Convenience function to get the `DefId` of a trait by path.
290 pub fn get_trait_def_id(cx: &LateContext<'_, '_>, path: &[&str]) -> Option<DefId> {
291 let def = match path_to_def(cx, path) {
297 def::Def::Trait(trait_id) => Some(trait_id),
302 /// Checks whether a type implements a trait.
303 /// See also `get_trait_def_id`.
304 pub fn implements_trait<'a, 'tcx>(
305 cx: &LateContext<'a, 'tcx>,
308 ty_params: &[Kind<'tcx>],
310 let ty = cx.tcx.erase_regions(&ty);
311 let obligation = cx.tcx.predicate_for_trait_def(
313 traits::ObligationCause::dummy(),
321 .enter(|infcx| infcx.predicate_must_hold_modulo_regions(&obligation))
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(cx: &LateContext<'_, '_>, hir_id: HirId) -> Option<TraitRef> {
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_by_hir_id(parent_impl);
345 if let hir::ItemKind::Impl(_, _, _, _, trait_ref, _, _) = &item.node;
346 then { return trait_ref.clone(); }
351 /// Checks whether this type implements `Drop`.
352 pub fn has_drop<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, ty: Ty<'tcx>) -> bool {
353 match ty.ty_adt_def() {
354 Some(def) => def.has_dtor(cx.tcx),
359 /// Resolves the definition of a node from its `HirId`.
360 pub fn resolve_node(cx: &LateContext<'_, '_>, qpath: &QPath, id: HirId) -> def::Def {
361 cx.tables.qpath_def(qpath, id)
364 /// Returns the method names and argument list of nested method call expressions that make up
366 pub fn method_calls<'a>(expr: &'a Expr, max_depth: usize) -> (Vec<Symbol>, Vec<&'a [Expr]>) {
367 let mut method_names = Vec::with_capacity(max_depth);
368 let mut arg_lists = Vec::with_capacity(max_depth);
370 let mut current = expr;
371 for _ in 0..max_depth {
372 if let ExprKind::MethodCall(path, _, args) = ¤t.node {
373 if args.iter().any(|e| in_macro(e.span)) {
376 method_names.push(path.ident.name);
377 arg_lists.push(&**args);
384 (method_names, arg_lists)
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 /// `matched_method_chain(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]>> {
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.node {
399 if path.ident.name == *method_name {
400 if args.iter().any(|e| in_macro(e.span)) {
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 {
419 if let Some((entry_fn_def_id, _)) = cx.tcx.entry_fn(LOCAL_CRATE) {
420 return def_id == entry_fn_def_id;
425 /// Gets the name of the item the expression is in, if available.
426 pub fn get_item_name(cx: &LateContext<'_, '_>, expr: &Expr) -> Option<Name> {
427 let parent_id = cx.tcx.hir().get_parent_item(expr.hir_id);
428 match cx.tcx.hir().find_by_hir_id(parent_id) {
429 Some(Node::Item(&Item { ref ident, .. })) => Some(ident.name),
430 Some(Node::TraitItem(&TraitItem { ident, .. })) | Some(Node::ImplItem(&ImplItem { ident, .. })) => {
437 /// Gets the name of a `Pat`, if any
438 pub fn get_pat_name(pat: &Pat) -> Option<Name> {
440 PatKind::Binding(.., ref spname, _) => Some(spname.name),
441 PatKind::Path(ref qpath) => single_segment_path(qpath).map(|ps| ps.ident.name),
442 PatKind::Box(ref p) | PatKind::Ref(ref p, _) => get_pat_name(&*p),
447 struct ContainsName {
452 impl<'tcx> Visitor<'tcx> for ContainsName {
453 fn visit_name(&mut self, _: Span, name: Name) {
454 if self.name == name {
458 fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'tcx> {
459 NestedVisitorMap::None
463 /// Checks if an `Expr` contains a certain name.
464 pub fn contains_name(name: Name, expr: &Expr) -> bool {
465 let mut cn = ContainsName { name, result: false };
470 /// Converts a span to a code snippet if available, otherwise use default.
472 /// This is useful if you want to provide suggestions for your lint or more generally, if you want
473 /// to convert a given `Span` to a `str`.
477 /// snippet(cx, expr.span, "..")
479 pub fn snippet<'a, 'b, T: LintContext<'b>>(cx: &T, span: Span, default: &'a str) -> Cow<'a, str> {
480 snippet_opt(cx, span).map_or_else(|| Cow::Borrowed(default), From::from)
483 /// Same as `snippet`, but it adapts the applicability level by following rules:
485 /// - Applicability level `Unspecified` will never be changed.
486 /// - If the span is inside a macro, change the applicability level to `MaybeIncorrect`.
487 /// - If the default value is used and the applicability level is `MachineApplicable`, change it to
488 /// `HasPlaceholders`
489 pub fn snippet_with_applicability<'a, 'b, T: LintContext<'b>>(
493 applicability: &mut Applicability,
495 if *applicability != Applicability::Unspecified && in_macro(span) {
496 *applicability = Applicability::MaybeIncorrect;
498 snippet_opt(cx, span).map_or_else(
500 if *applicability == Applicability::MachineApplicable {
501 *applicability = Applicability::HasPlaceholders;
503 Cow::Borrowed(default)
509 /// Same as `snippet`, but should only be used when it's clear that the input span is
510 /// not a macro argument.
511 pub fn snippet_with_macro_callsite<'a, 'b, T: LintContext<'b>>(cx: &T, span: Span, default: &'a str) -> Cow<'a, str> {
512 snippet(cx, span.source_callsite(), default)
515 /// Converts a span to a code snippet. Returns `None` if not available.
516 pub fn snippet_opt<'a, T: LintContext<'a>>(cx: &T, span: Span) -> Option<String> {
517 cx.sess().source_map().span_to_snippet(span).ok()
520 /// Converts a span (from a block) to a code snippet if available, otherwise use
522 /// This trims the code of indentation, except for the first line. Use it for
523 /// blocks or block-like
524 /// things which need to be printed as such.
528 /// snippet_block(cx, expr.span, "..")
530 pub fn snippet_block<'a, 'b, T: LintContext<'b>>(cx: &T, span: Span, default: &'a str) -> Cow<'a, str> {
531 let snip = snippet(cx, span, default);
532 trim_multiline(snip, true)
535 /// Same as `snippet_block`, but adapts the applicability level by the rules of
536 /// `snippet_with_applicabiliy`.
537 pub fn snippet_block_with_applicability<'a, 'b, T: LintContext<'b>>(
541 applicability: &mut Applicability,
543 let snip = snippet_with_applicability(cx, span, default, applicability);
544 trim_multiline(snip, true)
547 /// Returns a new Span that covers the full last line of the given Span
548 pub fn last_line_of_span<'a, T: LintContext<'a>>(cx: &T, span: Span) -> Span {
549 let source_map_and_line = cx.sess().source_map().lookup_line(span.lo()).unwrap();
550 let line_no = source_map_and_line.line;
551 let line_start = &source_map_and_line.sf.lines[line_no];
552 Span::new(*line_start, span.hi(), span.ctxt())
555 /// Like `snippet_block`, but add braces if the expr is not an `ExprKind::Block`.
556 /// Also takes an `Option<String>` which can be put inside the braces.
557 pub fn expr_block<'a, 'b, T: LintContext<'b>>(
560 option: Option<String>,
563 let code = snippet_block(cx, expr.span, default);
564 let string = option.unwrap_or_default();
565 if in_macro(expr.span) {
566 Cow::Owned(format!("{{ {} }}", snippet_with_macro_callsite(cx, expr.span, default)))
567 } else if let ExprKind::Block(_, _) = expr.node {
568 Cow::Owned(format!("{}{}", code, string))
569 } else if string.is_empty() {
570 Cow::Owned(format!("{{ {} }}", code))
572 Cow::Owned(format!("{{\n{};\n{}\n}}", code, string))
576 /// Trim indentation from a multiline string with possibility of ignoring the
578 pub fn trim_multiline(s: Cow<'_, str>, ignore_first: bool) -> Cow<'_, str> {
579 let s_space = trim_multiline_inner(s, ignore_first, ' ');
580 let s_tab = trim_multiline_inner(s_space, ignore_first, '\t');
581 trim_multiline_inner(s_tab, ignore_first, ' ')
584 fn trim_multiline_inner(s: Cow<'_, str>, ignore_first: bool, ch: char) -> Cow<'_, str> {
587 .skip(ignore_first as usize)
592 // ignore empty lines
593 Some(l.char_indices().find(|&(_, x)| x != ch).unwrap_or((l.len(), ch)).0)
603 if (ignore_first && i == 0) || l.is_empty() {
617 /// Gets a parent expressions if any – this is useful to constrain a lint.
618 pub fn get_parent_expr<'c>(cx: &'c LateContext<'_, '_>, e: &Expr) -> Option<&'c Expr> {
619 let map = &cx.tcx.hir();
620 let hir_id = e.hir_id;
621 let parent_id = map.get_parent_node_by_hir_id(hir_id);
622 if hir_id == parent_id {
625 map.find_by_hir_id(parent_id).and_then(|node| {
626 if let Node::Expr(parent) = node {
634 pub fn get_enclosing_block<'a, 'tcx: 'a>(cx: &LateContext<'a, 'tcx>, node: HirId) -> Option<&'tcx Block> {
635 let map = &cx.tcx.hir();
636 let node_id = map.hir_to_node_id(node);
637 let enclosing_node = map
638 .get_enclosing_scope(node_id)
639 .and_then(|enclosing_id| map.find(enclosing_id));
640 if let Some(node) = enclosing_node {
642 Node::Block(block) => Some(block),
644 node: ItemKind::Fn(_, _, _, eid),
647 | Node::ImplItem(&ImplItem {
648 node: ImplItemKind::Method(_, eid),
650 }) => match cx.tcx.hir().body(eid).value.node {
651 ExprKind::Block(ref block, _) => Some(block),
661 /// Returns the base type for HIR references and pointers.
662 pub fn walk_ptrs_hir_ty(ty: &hir::Ty) -> &hir::Ty {
664 TyKind::Ptr(ref mut_ty) | TyKind::Rptr(_, ref mut_ty) => walk_ptrs_hir_ty(&mut_ty.ty),
669 /// Returns the base type for references and raw pointers.
670 pub fn walk_ptrs_ty(ty: Ty<'_>) -> Ty<'_> {
672 ty::Ref(_, ty, _) => walk_ptrs_ty(ty),
677 /// Returns the base type for references and raw pointers, and count reference
679 pub fn walk_ptrs_ty_depth(ty: Ty<'_>) -> (Ty<'_>, usize) {
680 fn inner(ty: Ty<'_>, depth: usize) -> (Ty<'_>, usize) {
682 ty::Ref(_, ty, _) => inner(ty, depth + 1),
689 /// Checks whether the given expression is a constant literal of the given value.
690 pub fn is_integer_literal(expr: &Expr, value: u128) -> bool {
691 // FIXME: use constant folding
692 if let ExprKind::Lit(ref spanned) = expr.node {
693 if let LitKind::Int(v, _) = spanned.node {
700 /// Returns `true` if the given `Expr` has been coerced before.
702 /// Examples of coercions can be found in the Nomicon at
703 /// <https://doc.rust-lang.org/nomicon/coercions.html>.
705 /// See `rustc::ty::adjustment::Adjustment` and `rustc_typeck::check::coercion` for more
706 /// information on adjustments and coercions.
707 pub fn is_adjusted(cx: &LateContext<'_, '_>, e: &Expr) -> bool {
708 cx.tables.adjustments().get(e.hir_id).is_some()
711 /// Returns the pre-expansion span if is this comes from an expansion of the
713 /// See also `is_direct_expn_of`.
714 pub fn is_expn_of(mut span: Span, name: &str) -> Option<Span> {
716 let span_name_span = span
720 .map(|ei| (ei.format.name(), ei.call_site));
722 match span_name_span {
723 Some((mac_name, new_span)) if mac_name == name => return Some(new_span),
725 Some((_, new_span)) => span = new_span,
730 /// Returns the pre-expansion span if is this directly comes from an expansion
731 /// of the macro `name`.
732 /// The difference with `is_expn_of` is that in
736 /// `42` is considered expanded from `foo!` and `bar!` by `is_expn_of` but only
738 /// `is_direct_expn_of`.
739 pub fn is_direct_expn_of(span: Span, name: &str) -> Option<Span> {
740 let span_name_span = span
744 .map(|ei| (ei.format.name(), ei.call_site));
746 match span_name_span {
747 Some((mac_name, new_span)) if mac_name == name => Some(new_span),
752 /// Convenience function to get the return type of a function
753 pub fn return_ty<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, fn_item: hir::HirId) -> Ty<'tcx> {
754 let fn_def_id = cx.tcx.hir().local_def_id_from_hir_id(fn_item);
755 let ret_ty = cx.tcx.fn_sig(fn_def_id).output();
756 cx.tcx.erase_late_bound_regions(&ret_ty)
759 /// Checks if two types are the same.
761 /// This discards any lifetime annotations, too.
762 // FIXME: this works correctly for lifetimes bounds (`for <'a> Foo<'a>` == `for
764 // not for type parameters.
765 pub fn same_tys<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, a: Ty<'tcx>, b: Ty<'tcx>) -> bool {
766 let a = cx.tcx.erase_late_bound_regions(&Binder::bind(a));
767 let b = cx.tcx.erase_late_bound_regions(&Binder::bind(b));
770 .enter(|infcx| infcx.can_eq(cx.param_env, a, b).is_ok())
773 /// Returns `true` if the given type is an `unsafe` function.
774 pub fn type_is_unsafe_function<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, ty: Ty<'tcx>) -> bool {
776 ty::FnDef(..) | ty::FnPtr(_) => ty.fn_sig(cx.tcx).unsafety() == Unsafety::Unsafe,
781 pub fn is_copy<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, ty: Ty<'tcx>) -> bool {
782 ty.is_copy_modulo_regions(cx.tcx.global_tcx(), cx.param_env, DUMMY_SP)
785 /// Returns `true` if a pattern is refutable.
786 pub fn is_refutable(cx: &LateContext<'_, '_>, pat: &Pat) -> bool {
787 fn is_enum_variant(cx: &LateContext<'_, '_>, qpath: &QPath, id: HirId) -> bool {
789 cx.tables.qpath_def(qpath, id),
790 def::Def::Variant(..) | def::Def::VariantCtor(..)
794 fn are_refutable<'a, I: Iterator<Item = &'a Pat>>(cx: &LateContext<'_, '_>, mut i: I) -> bool {
795 i.any(|pat| is_refutable(cx, pat))
799 PatKind::Binding(..) | PatKind::Wild => false,
800 PatKind::Box(ref pat) | PatKind::Ref(ref pat, _) => is_refutable(cx, pat),
801 PatKind::Lit(..) | PatKind::Range(..) => true,
802 PatKind::Path(ref qpath) => is_enum_variant(cx, qpath, pat.hir_id),
803 PatKind::Tuple(ref pats, _) => are_refutable(cx, pats.iter().map(|pat| &**pat)),
804 PatKind::Struct(ref qpath, ref fields, _) => {
805 if is_enum_variant(cx, qpath, pat.hir_id) {
808 are_refutable(cx, fields.iter().map(|field| &*field.node.pat))
811 PatKind::TupleStruct(ref qpath, ref pats, _) => {
812 if is_enum_variant(cx, qpath, pat.hir_id) {
815 are_refutable(cx, pats.iter().map(|pat| &**pat))
818 PatKind::Slice(ref head, ref middle, ref tail) => {
819 are_refutable(cx, head.iter().chain(middle).chain(tail.iter()).map(|pat| &**pat))
824 /// Checks for the `#[automatically_derived]` attribute all `#[derive]`d
825 /// implementations have.
826 pub fn is_automatically_derived(attrs: &[ast::Attribute]) -> bool {
827 attr::contains_name(attrs, "automatically_derived")
830 /// Remove blocks around an expression.
832 /// Ie. `x`, `{ x }` and `{{{{ x }}}}` all give `x`. `{ x; y }` and `{}` return
834 pub fn remove_blocks(expr: &Expr) -> &Expr {
835 if let ExprKind::Block(ref block, _) = expr.node {
836 if block.stmts.is_empty() {
837 if let Some(ref expr) = block.expr {
850 pub fn is_self(slf: &Arg) -> bool {
851 if let PatKind::Binding(.., name, _) = slf.pat.node {
852 name.name == keywords::SelfLower.name()
858 pub fn is_self_ty(slf: &hir::Ty) -> bool {
860 if let TyKind::Path(ref qp) = slf.node;
861 if let QPath::Resolved(None, ref path) = *qp;
862 if let Def::SelfTy(..) = path.def;
870 pub fn iter_input_pats<'tcx>(decl: &FnDecl, body: &'tcx Body) -> impl Iterator<Item = &'tcx Arg> {
871 (0..decl.inputs.len()).map(move |i| &body.arguments[i])
874 /// Checks if a given expression is a match expression
875 /// expanded from `?` operator or `try` macro.
876 pub fn is_try<'a>(cx: &'_ LateContext<'_, '_>, expr: &'a Expr) -> Option<&'a Expr> {
877 fn is_ok(cx: &'_ LateContext<'_, '_>, arm: &Arm) -> bool {
879 if let PatKind::TupleStruct(ref path, ref pat, None) = arm.pats[0].node;
880 if match_qpath(path, &paths::RESULT_OK[1..]);
881 if let PatKind::Binding(_, hir_id, _, None) = pat[0].node;
882 if let ExprKind::Path(QPath::Resolved(None, ref path)) = arm.body.node;
883 if let Def::Local(lid) = path.def;
884 if cx.tcx.hir().node_to_hir_id(lid) == hir_id;
892 fn is_err(arm: &Arm) -> bool {
893 if let PatKind::TupleStruct(ref path, _, _) = arm.pats[0].node {
894 match_qpath(path, &paths::RESULT_ERR[1..])
900 if let ExprKind::Match(_, ref arms, ref source) = expr.node {
901 // desugared from a `?` operator
902 if let MatchSource::TryDesugar = *source {
908 if arms[0].pats.len() == 1 && arms[0].guard.is_none();
909 if arms[1].pats.len() == 1 && arms[1].guard.is_none();
910 if (is_ok(cx, &arms[0]) && is_err(&arms[1])) ||
911 (is_ok(cx, &arms[1]) && is_err(&arms[0]));
921 /// Returns `true` if the lint is allowed in the current context
923 /// Useful for skipping long running code when it's unnecessary
924 pub fn is_allowed(cx: &LateContext<'_, '_>, lint: &'static Lint, id: HirId) -> bool {
925 cx.tcx.lint_level_at_node(lint, id).0 == Level::Allow
928 pub fn get_arg_name(pat: &Pat) -> Option<ast::Name> {
930 PatKind::Binding(.., ident, None) => Some(ident.name),
931 PatKind::Ref(ref subpat, _) => get_arg_name(subpat),
936 pub fn int_bits(tcx: TyCtxt<'_, '_, '_>, ity: ast::IntTy) -> u64 {
937 layout::Integer::from_attr(&tcx, attr::IntType::SignedInt(ity))
942 #[allow(clippy::cast_possible_wrap)]
943 /// Turn a constant int byte representation into an i128
944 pub fn sext(tcx: TyCtxt<'_, '_, '_>, u: u128, ity: ast::IntTy) -> i128 {
945 let amt = 128 - int_bits(tcx, ity);
946 ((u as i128) << amt) >> amt
949 #[allow(clippy::cast_sign_loss)]
950 /// clip unused bytes
951 pub fn unsext(tcx: TyCtxt<'_, '_, '_>, u: i128, ity: ast::IntTy) -> u128 {
952 let amt = 128 - int_bits(tcx, ity);
953 ((u as u128) << amt) >> amt
956 /// clip unused bytes
957 pub fn clip(tcx: TyCtxt<'_, '_, '_>, u: u128, ity: ast::UintTy) -> u128 {
958 let bits = layout::Integer::from_attr(&tcx, attr::IntType::UnsignedInt(ity))
961 let amt = 128 - bits;
965 /// Removes block comments from the given `Vec` of lines.
970 /// without_block_comments(vec!["/*", "foo", "*/"]);
973 /// without_block_comments(vec!["bar", "/*", "foo", "*/"]);
974 /// // => vec!["bar"]
976 pub fn without_block_comments(lines: Vec<&str>) -> Vec<&str> {
977 let mut without = vec![];
979 let mut nest_level = 0;
982 if line.contains("/*") {
985 } else if line.contains("*/") {
998 pub fn any_parent_is_automatically_derived(tcx: TyCtxt<'_, '_, '_>, node: HirId) -> bool {
999 let map = &tcx.hir();
1000 let mut prev_enclosing_node = None;
1001 let mut enclosing_node = node;
1002 while Some(enclosing_node) != prev_enclosing_node {
1003 if is_automatically_derived(map.attrs_by_hir_id(enclosing_node)) {
1006 prev_enclosing_node = Some(enclosing_node);
1007 enclosing_node = map.get_parent_item(enclosing_node);
1012 /// Returns true if ty has `iter` or `iter_mut` methods
1013 pub fn has_iter_method(cx: &LateContext<'_, '_>, probably_ref_ty: ty::Ty<'_>) -> Option<&'static str> {
1014 // FIXME: instead of this hard-coded list, we should check if `<adt>::iter`
1015 // exists and has the desired signature. Unfortunately FnCtxt is not exported
1016 // so we can't use its `lookup_method` method.
1017 static INTO_ITER_COLLECTIONS: [&[&str]; 13] = [
1024 &paths::LINKED_LIST,
1025 &paths::BINARY_HEAP,
1033 let ty_to_check = match probably_ref_ty.sty {
1034 ty::Ref(_, ty_to_check, _) => ty_to_check,
1035 _ => probably_ref_ty,
1038 let def_id = match ty_to_check.sty {
1039 ty::Array(..) => return Some("array"),
1040 ty::Slice(..) => return Some("slice"),
1041 ty::Adt(adt, _) => adt.did,
1045 for path in &INTO_ITER_COLLECTIONS {
1046 if match_def_path(cx.tcx, def_id, path) {
1047 return Some(path.last().unwrap());
1055 use super::{trim_multiline, without_block_comments};
1058 fn test_trim_multiline_single_line() {
1059 assert_eq!("", trim_multiline("".into(), false));
1060 assert_eq!("...", trim_multiline("...".into(), false));
1061 assert_eq!("...", trim_multiline(" ...".into(), false));
1062 assert_eq!("...", trim_multiline("\t...".into(), false));
1063 assert_eq!("...", trim_multiline("\t\t...".into(), false));
1068 fn test_trim_multiline_block() {
1074 }", trim_multiline(" if x {
1084 }", trim_multiline(" if x {
1093 fn test_trim_multiline_empty_line() {
1100 }", trim_multiline(" if x {
1109 fn test_without_block_comments_lines_without_block_comments() {
1110 let result = without_block_comments(vec!["/*", "", "*/"]);
1111 println!("result: {:?}", result);
1112 assert!(result.is_empty());
1114 let result = without_block_comments(vec!["", "/*", "", "*/", "#[crate_type = \"lib\"]", "/*", "", "*/", ""]);
1115 assert_eq!(result, vec!["", "#[crate_type = \"lib\"]", ""]);
1117 let result = without_block_comments(vec!["/* rust", "", "*/"]);
1118 assert!(result.is_empty());
1120 let result = without_block_comments(vec!["/* one-line comment */"]);
1121 assert!(result.is_empty());
1123 let result = without_block_comments(vec!["/* nested", "/* multi-line", "comment", "*/", "test", "*/"]);
1124 assert!(result.is_empty());
1126 let result = without_block_comments(vec!["/* nested /* inline /* comment */ test */ */"]);
1127 assert!(result.is_empty());
1129 let result = without_block_comments(vec!["foo", "bar", "baz"]);
1130 assert_eq!(result, vec!["foo", "bar", "baz"]);