1 // Copyright 2014-2018 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution.
4 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
5 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
6 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
7 // option. This file may not be copied, modified, or distributed
8 // except according to those terms.
11 use crate::reexport::*;
13 use if_chain::if_chain;
14 use crate::rustc::hir;
15 use crate::rustc::hir::*;
16 use crate::rustc::hir::def_id::{DefId, CRATE_DEF_INDEX};
17 use crate::rustc::hir::def::Def;
18 use crate::rustc::hir::intravisit::{NestedVisitorMap, Visitor};
19 use crate::rustc::hir::Node;
20 use crate::rustc::lint::{LateContext, Level, Lint, LintContext};
21 use crate::rustc::session::Session;
22 use crate::rustc::traits;
23 use crate::rustc::ty::{self, Binder, Ty, TyCtxt, layout::{self, IntegerExt}, subst::Kind};
24 use crate::rustc_errors::{Applicability, CodeSuggestion, Substitution, SubstitutionPart};
28 use std::str::FromStr;
30 use crate::syntax::ast::{self, LitKind};
31 use crate::syntax::attr;
32 use crate::syntax::source_map::{Span, DUMMY_SP};
33 use crate::syntax::errors::DiagnosticBuilder;
34 use crate::syntax::symbol::{keywords, Symbol};
45 pub mod internal_lints;
49 pub use self::hir_utils::{SpanlessEq, SpanlessHash};
53 /// Returns true if the two spans come from differing expansions (i.e. one is
54 /// from a macro and one
56 pub fn differing_macro_contexts(lhs: Span, rhs: Span) -> bool {
57 rhs.ctxt() != lhs.ctxt()
60 pub fn in_constant(cx: &LateContext<'_, '_>, id: NodeId) -> bool {
61 let parent_id = cx.tcx.hir.get_parent(id);
62 match cx.tcx.hir.body_owner_kind(parent_id) {
63 hir::BodyOwnerKind::Fn => false,
64 hir::BodyOwnerKind::Const | hir::BodyOwnerKind::Static(..) => true,
68 /// Returns true if this `expn_info` was expanded by any macro.
69 pub fn in_macro(span: Span) -> bool {
70 span.ctxt().outer().expn_info().is_some()
73 /// Check if a `DefId`'s path matches the given absolute type path usage.
77 /// match_def_path(cx.tcx, id, &["core", "option", "Option"])
80 /// See also the `paths` module.
81 pub fn match_def_path(tcx: TyCtxt<'_, '_, '_>, def_id: DefId, path: &[&str]) -> bool {
82 use crate::syntax::symbol;
85 struct AbsolutePathBuffer {
86 names: Vec<symbol::LocalInternedString>,
89 impl ty::item_path::ItemPathBuffer for AbsolutePathBuffer {
90 fn root_mode(&self) -> &ty::item_path::RootMode {
91 const ABSOLUTE: &ty::item_path::RootMode = &ty::item_path::RootMode::Absolute;
95 fn push(&mut self, text: &str) {
96 self.names.push(symbol::Symbol::intern(text).as_str());
100 let mut apb = AbsolutePathBuffer { names: vec![] };
102 tcx.push_item_path(&mut apb, def_id, false);
104 apb.names.len() == path.len()
108 .all(|(a, &b)| *a == *b)
111 /// Check if type is struct, enum or union type with given def path.
112 pub fn match_type(cx: &LateContext<'_, '_>, ty: Ty<'_>, path: &[&str]) -> bool {
114 ty::Adt(adt, _) => match_def_path(cx.tcx, adt.did, path),
119 /// Check if the method call given in `expr` belongs to given trait.
120 pub fn match_trait_method(cx: &LateContext<'_, '_>, expr: &Expr, path: &[&str]) -> bool {
121 let method_call = cx.tables.type_dependent_defs()[expr.hir_id];
122 let trt_id = cx.tcx.trait_of_item(method_call.def_id());
123 if let Some(trt_id) = trt_id {
124 match_def_path(cx.tcx, trt_id, path)
130 /// Check if an expression references a variable of the given name.
131 pub fn match_var(expr: &Expr, var: Name) -> bool {
132 if let ExprKind::Path(QPath::Resolved(None, ref path)) = expr.node {
133 if path.segments.len() == 1 && path.segments[0].ident.name == var {
141 pub fn last_path_segment(path: &QPath) -> &PathSegment {
143 QPath::Resolved(_, ref path) => path.segments
145 .expect("A path must have at least one segment"),
146 QPath::TypeRelative(_, ref seg) => seg,
150 pub fn single_segment_path(path: &QPath) -> Option<&PathSegment> {
152 QPath::Resolved(_, ref path) if path.segments.len() == 1 => Some(&path.segments[0]),
153 QPath::Resolved(..) => None,
154 QPath::TypeRelative(_, ref seg) => Some(seg),
158 /// Match a `Path` against a slice of segment string literals.
162 /// match_qpath(path, &["std", "rt", "begin_unwind"])
164 pub fn match_qpath(path: &QPath, segments: &[&str]) -> bool {
166 QPath::Resolved(_, ref path) => match_path(path, segments),
167 QPath::TypeRelative(ref ty, ref segment) => match ty.node {
168 TyKind::Path(ref inner_path) => {
169 !segments.is_empty() && match_qpath(inner_path, &segments[..(segments.len() - 1)])
170 && segment.ident.name == segments[segments.len() - 1]
177 pub fn match_path(path: &Path, segments: &[&str]) -> bool {
181 .zip(segments.iter().rev())
182 .all(|(a, b)| a.ident.name == *b)
185 /// Match a `Path` against a slice of segment string literals, e.g.
189 /// match_qpath(path, &["std", "rt", "begin_unwind"])
191 pub fn match_path_ast(path: &ast::Path, segments: &[&str]) -> bool {
195 .zip(segments.iter().rev())
196 .all(|(a, b)| a.ident.name == *b)
199 /// Get the definition associated to a path.
200 pub fn path_to_def(cx: &LateContext<'_, '_>, path: &[&str]) -> Option<def::Def> {
201 let crates = cx.tcx.crates();
204 .find(|&&krate| cx.tcx.crate_name(krate) == path[0]);
205 if let Some(krate) = krate {
208 index: CRATE_DEF_INDEX,
210 let mut items = cx.tcx.item_children(krate);
211 let mut path_it = path.iter().skip(1).peekable();
214 let segment = match path_it.next() {
215 Some(segment) => segment,
219 for item in mem::replace(&mut items, Rc::new(vec![])).iter() {
220 if item.ident.name == *segment {
221 if path_it.peek().is_none() {
222 return Some(item.def);
225 items = cx.tcx.item_children(item.def.def_id());
235 /// Convenience function to get the `DefId` of a trait by path.
236 pub fn get_trait_def_id(cx: &LateContext<'_, '_>, path: &[&str]) -> Option<DefId> {
237 let def = match path_to_def(cx, path) {
243 def::Def::Trait(trait_id) => Some(trait_id),
248 /// Check whether a type implements a trait.
249 /// See also `get_trait_def_id`.
250 pub fn implements_trait<'a, 'tcx>(
251 cx: &LateContext<'a, 'tcx>,
254 ty_params: &[Kind<'tcx>],
256 let ty = cx.tcx.erase_regions(&ty);
259 .predicate_for_trait_def(cx.param_env, traits::ObligationCause::dummy(), trait_id, 0, ty, ty_params);
260 cx.tcx.infer_ctxt().enter(|infcx| infcx.predicate_must_hold(&obligation))
263 /// Check whether this type implements Drop.
264 pub fn has_drop(cx: &LateContext<'_, '_>, expr: &Expr) -> bool {
265 let struct_ty = cx.tables.expr_ty(expr);
266 match struct_ty.ty_adt_def() {
267 Some(def) => def.has_dtor(cx.tcx),
272 /// Resolve the definition of a node from its `HirId`.
273 pub fn resolve_node(cx: &LateContext<'_, '_>, qpath: &QPath, id: HirId) -> def::Def {
274 cx.tables.qpath_def(qpath, id)
277 /// Return the method names and argument list of nested method call expressions that make up
279 pub fn method_calls<'a>(expr: &'a Expr, max_depth: usize) -> (Vec<Symbol>, Vec<&'a [Expr]>) {
280 let mut method_names = Vec::with_capacity(max_depth);
281 let mut arg_lists = Vec::with_capacity(max_depth);
283 let mut current = expr;
284 for _ in 0..max_depth {
285 if let ExprKind::MethodCall(path, _, args) = ¤t.node {
286 if args.iter().any(|e| in_macro(e.span)) {
289 method_names.push(path.ident.name);
290 arg_lists.push(&**args);
297 (method_names, arg_lists)
300 /// Match an `Expr` against a chain of methods, and return the matched `Expr`s.
302 /// For example, if `expr` represents the `.baz()` in `foo.bar().baz()`,
303 /// `matched_method_chain(expr, &["bar", "baz"])` will return a `Vec`
304 /// containing the `Expr`s for
305 /// `.bar()` and `.baz()`
306 pub fn method_chain_args<'a>(expr: &'a Expr, methods: &[&str]) -> Option<Vec<&'a [Expr]>> {
307 let mut current = expr;
308 let mut matched = Vec::with_capacity(methods.len());
309 for method_name in methods.iter().rev() {
310 // method chains are stored last -> first
311 if let ExprKind::MethodCall(ref path, _, ref args) = current.node {
312 if path.ident.name == *method_name {
313 if args.iter().any(|e| in_macro(e.span)) {
316 matched.push(&**args); // build up `matched` backwards
317 current = &args[0] // go to parent expression
325 matched.reverse(); // reverse `matched`, so that it is in the same order as `methods`
330 /// Get the name of the item the expression is in, if available.
331 pub fn get_item_name(cx: &LateContext<'_, '_>, expr: &Expr) -> Option<Name> {
332 let parent_id = cx.tcx.hir.get_parent(expr.id);
333 match cx.tcx.hir.find(parent_id) {
334 Some(Node::Item(&Item { ref name, .. })) => Some(*name),
335 Some(Node::TraitItem(&TraitItem { ident, .. })) |
336 Some(Node::ImplItem(&ImplItem { ident, .. })) => Some(ident.name),
341 /// Get the name of a `Pat`, if any
342 pub fn get_pat_name(pat: &Pat) -> Option<Name> {
344 PatKind::Binding(_, _, ref spname, _) => Some(spname.name),
345 PatKind::Path(ref qpath) => single_segment_path(qpath).map(|ps| ps.ident.name),
346 PatKind::Box(ref p) | PatKind::Ref(ref p, _) => get_pat_name(&*p),
351 struct ContainsName {
356 impl<'tcx> Visitor<'tcx> for ContainsName {
357 fn visit_name(&mut self, _: Span, name: Name) {
358 if self.name == name {
362 fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'tcx> {
363 NestedVisitorMap::None
367 /// check if an `Expr` contains a certain name
368 pub fn contains_name(name: Name, expr: &Expr) -> bool {
369 let mut cn = ContainsName {
378 /// Convert a span to a code snippet if available, otherwise use default.
382 /// snippet(cx, expr.span, "..")
384 pub fn snippet<'a, 'b, T: LintContext<'b>>(cx: &T, span: Span, default: &'a str) -> Cow<'a, str> {
385 snippet_opt(cx, span).map_or_else(|| Cow::Borrowed(default), From::from)
388 /// Same as `snippet`, but should only be used when it's clear that the input span is
389 /// not a macro argument.
390 pub fn snippet_with_macro_callsite<'a, 'b, T: LintContext<'b>>(cx: &T, span: Span, default: &'a str) -> Cow<'a, str> {
391 snippet(cx, span.source_callsite(), default)
394 /// Convert a span to a code snippet. Returns `None` if not available.
395 pub fn snippet_opt<'a, T: LintContext<'a>>(cx: &T, span: Span) -> Option<String> {
396 cx.sess().source_map().span_to_snippet(span).ok()
399 /// Convert a span (from a block) to a code snippet if available, otherwise use
401 /// This trims the code of indentation, except for the first line. Use it for
402 /// blocks or block-like
403 /// things which need to be printed as such.
407 /// snippet(cx, expr.span, "..")
409 pub fn snippet_block<'a, 'b, T: LintContext<'b>>(cx: &T, span: Span, default: &'a str) -> Cow<'a, str> {
410 let snip = snippet(cx, span, default);
411 trim_multiline(snip, true)
414 /// Returns a new Span that covers the full last line of the given Span
415 pub fn last_line_of_span<'a, T: LintContext<'a>>(cx: &T, span: Span) -> Span {
416 let file_map_and_line = cx.sess().source_map().lookup_line(span.lo()).unwrap();
417 let line_no = file_map_and_line.line;
418 let line_start = &file_map_and_line.sf.lines[line_no];
419 Span::new(*line_start, span.hi(), span.ctxt())
422 /// Like `snippet_block`, but add braces if the expr is not an `ExprKind::Block`.
423 /// Also takes an `Option<String>` which can be put inside the braces.
424 pub fn expr_block<'a, 'b, T: LintContext<'b>>(
427 option: Option<String>,
430 let code = snippet_block(cx, expr.span, default);
431 let string = option.unwrap_or_default();
432 if in_macro(expr.span) {
433 Cow::Owned(format!("{{ {} }}", snippet_with_macro_callsite(cx, expr.span, default)))
435 else if let ExprKind::Block(_, _) = expr.node {
436 Cow::Owned(format!("{}{}", code, string))
437 } else if string.is_empty() {
438 Cow::Owned(format!("{{ {} }}", code))
440 Cow::Owned(format!("{{\n{};\n{}\n}}", code, string))
444 /// Trim indentation from a multiline string with possibility of ignoring the
446 pub fn trim_multiline(s: Cow<'_, str>, ignore_first: bool) -> Cow<'_, str> {
447 let s_space = trim_multiline_inner(s, ignore_first, ' ');
448 let s_tab = trim_multiline_inner(s_space, ignore_first, '\t');
449 trim_multiline_inner(s_tab, ignore_first, ' ')
452 fn trim_multiline_inner(s: Cow<'_, str>, ignore_first: bool, ch: char) -> Cow<'_, str> {
454 .skip(ignore_first as usize)
459 // ignore empty lines
462 .find(|&(_, x)| x != ch)
463 .unwrap_or((l.len(), ch))
475 if (ignore_first && i == 0) || l.is_empty() {
489 /// Get a parent expressions if any – this is useful to constrain a lint.
490 pub fn get_parent_expr<'c>(cx: &'c LateContext<'_, '_>, e: &Expr) -> Option<&'c Expr> {
491 let map = &cx.tcx.hir;
492 let node_id: NodeId = e.id;
493 let parent_id: NodeId = map.get_parent_node(node_id);
494 if node_id == parent_id {
497 map.find(parent_id).and_then(|node| {
498 if let Node::Expr(parent) = node {
506 pub fn get_enclosing_block<'a, 'tcx: 'a>(cx: &LateContext<'a, 'tcx>, node: NodeId) -> Option<&'tcx Block> {
507 let map = &cx.tcx.hir;
508 let enclosing_node = map.get_enclosing_scope(node)
509 .and_then(|enclosing_id| map.find(enclosing_id));
510 if let Some(node) = enclosing_node {
512 Node::Block(block) => Some(block),
514 node: ItemKind::Fn(_, _, _, eid),
516 }) | Node::ImplItem(&ImplItem {
517 node: ImplItemKind::Method(_, eid),
519 }) => match cx.tcx.hir.body(eid).value.node {
520 ExprKind::Block(ref block, _) => Some(block),
530 pub struct DiagnosticWrapper<'a>(pub DiagnosticBuilder<'a>);
532 impl<'a> Drop for DiagnosticWrapper<'a> {
538 impl<'a> DiagnosticWrapper<'a> {
539 fn docs_link(&mut self, lint: &'static Lint) {
540 if env::var("CLIPPY_DISABLE_DOCS_LINKS").is_err() {
541 self.0.help(&format!(
542 "for further information visit https://rust-lang.github.io/rust-clippy/{}/index.html#{}",
543 &option_env!("RUST_RELEASE_NUM").map_or("master".to_string(), |n| {
544 // extract just major + minor version and ignore patch versions
545 format!("rust-{}", n.rsplitn(2, '.').nth(1).unwrap())
547 lint.name_lower().replacen("clippy::", "", 1)
553 pub fn span_lint<'a, T: LintContext<'a>>(cx: &T, lint: &'static Lint, sp: Span, msg: &str) {
554 DiagnosticWrapper(cx.struct_span_lint(lint, sp, msg)).docs_link(lint);
557 pub fn span_help_and_lint<'a, 'tcx: 'a, T: LintContext<'tcx>>(
564 let mut db = DiagnosticWrapper(cx.struct_span_lint(lint, span, msg));
569 pub fn span_note_and_lint<'a, 'tcx: 'a, T: LintContext<'tcx>>(
577 let mut db = DiagnosticWrapper(cx.struct_span_lint(lint, span, msg));
578 if note_span == span {
581 db.0.span_note(note_span, note);
586 pub fn span_lint_and_then<'a, 'tcx: 'a, T: LintContext<'tcx>, F>(
593 F: for<'b> FnOnce(&mut DiagnosticBuilder<'b>),
595 let mut db = DiagnosticWrapper(cx.struct_span_lint(lint, sp, msg));
600 pub fn span_lint_node(cx: &LateContext<'_, '_>, lint: &'static Lint, node: NodeId, sp: Span, msg: &str) {
601 DiagnosticWrapper(cx.tcx.struct_span_lint_node(lint, node, sp, msg)).docs_link(lint);
604 pub fn span_lint_node_and_then(
605 cx: &LateContext<'_, '_>,
610 f: impl FnOnce(&mut DiagnosticBuilder<'_>),
612 let mut db = DiagnosticWrapper(cx.tcx.struct_span_lint_node(lint, node, sp, msg));
617 /// Add a span lint with a suggestion on how to fix it.
619 /// These suggestions can be parsed by rustfix to allow it to automatically fix your code.
620 /// In the example below, `help` is `"try"` and `sugg` is the suggested replacement `".any(|x| x > 2)"`.
623 /// error: This `.fold` can be more succinctly expressed as `.any`
624 /// --> $DIR/methods.rs:390:13
626 /// 390 | let _ = (0..3).fold(false, |acc, x| acc || x > 2);
627 /// | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: try: `.any(|x| x > 2)`
629 /// = note: `-D fold-any` implied by `-D warnings`
631 pub fn span_lint_and_sugg<'a, 'tcx: 'a, T: LintContext<'tcx>>(
639 span_lint_and_then(cx, lint, sp, msg, |db| {
640 db.span_suggestion_with_applicability(sp, help, sugg, Applicability::Unspecified);
644 /// Create a suggestion made from several `span → replacement`.
646 /// Note: in the JSON format (used by `compiletest_rs`), the help message will
648 /// replacement. In human-readable format though, it only appears once before
649 /// the whole suggestion.
650 pub fn multispan_sugg<I>(db: &mut DiagnosticBuilder<'_>, help_msg: String, sugg: I)
652 I: IntoIterator<Item = (Span, String)>,
654 let sugg = CodeSuggestion {
657 parts: sugg.into_iter()
658 .map(|(span, snippet)| {
668 show_code_when_inline: true,
669 applicability: Applicability::Unspecified,
671 db.suggestions.push(sugg);
674 /// Return the base type for HIR references and pointers.
675 pub fn walk_ptrs_hir_ty(ty: &hir::Ty) -> &hir::Ty {
677 TyKind::Ptr(ref mut_ty) | TyKind::Rptr(_, ref mut_ty) => walk_ptrs_hir_ty(&mut_ty.ty),
682 /// Return the base type for references and raw pointers.
683 pub fn walk_ptrs_ty(ty: Ty<'_>) -> Ty<'_> {
685 ty::Ref(_, ty, _) => walk_ptrs_ty(ty),
690 /// Return the base type for references and raw pointers, and count reference
692 pub fn walk_ptrs_ty_depth(ty: Ty<'_>) -> (Ty<'_>, usize) {
693 fn inner(ty: Ty<'_>, depth: usize) -> (Ty<'_>, usize) {
695 ty::Ref(_, ty, _) => inner(ty, depth + 1),
702 /// Check whether the given expression is a constant literal of the given value.
703 pub fn is_integer_literal(expr: &Expr, value: u128) -> bool {
704 // FIXME: use constant folding
705 if let ExprKind::Lit(ref spanned) = expr.node {
706 if let LitKind::Int(v, _) = spanned.node {
713 pub fn is_adjusted(cx: &LateContext<'_, '_>, e: &Expr) -> bool {
714 cx.tables.adjustments().get(e.hir_id).is_some()
717 pub struct LimitStack {
721 impl Drop for LimitStack {
723 assert_eq!(self.stack.len(), 1);
728 pub fn new(limit: u64) -> Self {
729 Self { stack: vec![limit] }
731 pub fn limit(&self) -> u64 {
734 .expect("there should always be a value in the stack")
736 pub fn push_attrs(&mut self, sess: &Session, attrs: &[ast::Attribute], name: &'static str) {
737 let stack = &mut self.stack;
738 parse_attrs(sess, attrs, name, |val| stack.push(val));
740 pub fn pop_attrs(&mut self, sess: &Session, attrs: &[ast::Attribute], name: &'static str) {
741 let stack = &mut self.stack;
742 parse_attrs(sess, attrs, name, |val| assert_eq!(stack.pop(), Some(val)));
746 pub fn get_attr<'a>(attrs: &'a [ast::Attribute], name: &'static str) -> impl Iterator<Item = &'a ast::Attribute> {
747 attrs.iter().filter(move |attr|
748 attr.path.segments.len() == 2 &&
749 attr.path.segments[0].ident.to_string() == "clippy" &&
750 attr.path.segments[1].ident.to_string() == name)
753 fn parse_attrs<F: FnMut(u64)>(sess: &Session, attrs: &[ast::Attribute], name: &'static str, mut f: F) {
754 for attr in get_attr(attrs, name) {
755 if let Some(ref value) = attr.value_str() {
756 if let Ok(value) = FromStr::from_str(&value.as_str()) {
759 sess.span_err(attr.span, "not a number");
762 sess.span_err(attr.span, "bad clippy attribute");
767 /// Return the pre-expansion span if is this comes from an expansion of the
769 /// See also `is_direct_expn_of`.
770 pub fn is_expn_of(mut span: Span, name: &str) -> Option<Span> {
772 let span_name_span = span.ctxt()
775 .map(|ei| (ei.format.name(), ei.call_site));
777 match span_name_span {
778 Some((mac_name, new_span)) if mac_name == name => return Some(new_span),
780 Some((_, new_span)) => span = new_span,
785 /// Return the pre-expansion span if is this directly comes from an expansion
786 /// of the macro `name`.
787 /// The difference with `is_expn_of` is that in
791 /// `42` is considered expanded from `foo!` and `bar!` by `is_expn_of` but only
793 /// `is_direct_expn_of`.
794 pub fn is_direct_expn_of(span: Span, name: &str) -> Option<Span> {
795 let span_name_span = span.ctxt()
798 .map(|ei| (ei.format.name(), ei.call_site));
800 match span_name_span {
801 Some((mac_name, new_span)) if mac_name == name => Some(new_span),
806 /// Convenience function to get the return type of a function
807 pub fn return_ty<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, fn_item: NodeId) -> Ty<'tcx> {
808 let fn_def_id = cx.tcx.hir.local_def_id(fn_item);
809 let ret_ty = cx.tcx.fn_sig(fn_def_id).output();
810 cx.tcx.erase_late_bound_regions(&ret_ty)
813 /// Check if two types are the same.
815 /// This discards any lifetime annotations, too.
816 // FIXME: this works correctly for lifetimes bounds (`for <'a> Foo<'a>` == `for
818 // not for type parameters.
819 pub fn same_tys<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, a: Ty<'tcx>, b: Ty<'tcx>) -> bool {
820 let a = cx.tcx.erase_late_bound_regions(&Binder::bind(a));
821 let b = cx.tcx.erase_late_bound_regions(&Binder::bind(b));
824 .enter(|infcx| infcx.can_eq(cx.param_env, a, b).is_ok())
827 /// Return whether the given type is an `unsafe` function.
828 pub fn type_is_unsafe_function<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, ty: Ty<'tcx>) -> bool {
830 ty::FnDef(..) | ty::FnPtr(_) => ty.fn_sig(cx.tcx).unsafety() == Unsafety::Unsafe,
835 pub fn is_copy<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, ty: Ty<'tcx>) -> bool {
836 !ty.moves_by_default(cx.tcx.global_tcx(), cx.param_env, DUMMY_SP)
839 /// Return whether a pattern is refutable.
840 pub fn is_refutable(cx: &LateContext<'_, '_>, pat: &Pat) -> bool {
841 fn is_enum_variant(cx: &LateContext<'_, '_>, qpath: &QPath, id: HirId) -> bool {
843 cx.tables.qpath_def(qpath, id),
844 def::Def::Variant(..) | def::Def::VariantCtor(..)
848 fn are_refutable<'a, I: Iterator<Item = &'a Pat>>(cx: &LateContext<'_, '_>, mut i: I) -> bool {
849 i.any(|pat| is_refutable(cx, pat))
853 PatKind::Binding(..) | PatKind::Wild => false,
854 PatKind::Box(ref pat) | PatKind::Ref(ref pat, _) => is_refutable(cx, pat),
855 PatKind::Lit(..) | PatKind::Range(..) => true,
856 PatKind::Path(ref qpath) => is_enum_variant(cx, qpath, pat.hir_id),
857 PatKind::Tuple(ref pats, _) => are_refutable(cx, pats.iter().map(|pat| &**pat)),
858 PatKind::Struct(ref qpath, ref fields, _) => if is_enum_variant(cx, qpath, pat.hir_id) {
861 are_refutable(cx, fields.iter().map(|field| &*field.node.pat))
863 PatKind::TupleStruct(ref qpath, ref pats, _) => if is_enum_variant(cx, qpath, pat.hir_id) {
866 are_refutable(cx, pats.iter().map(|pat| &**pat))
868 PatKind::Slice(ref head, ref middle, ref tail) => are_refutable(
878 /// Checks for the `#[automatically_derived]` attribute all `#[derive]`d
879 /// implementations have.
880 pub fn is_automatically_derived(attrs: &[ast::Attribute]) -> bool {
881 attr::contains_name(attrs, "automatically_derived")
884 /// Remove blocks around an expression.
886 /// Ie. `x`, `{ x }` and `{{{{ x }}}}` all give `x`. `{ x; y }` and `{}` return
888 pub fn remove_blocks(expr: &Expr) -> &Expr {
889 if let ExprKind::Block(ref block, _) = expr.node {
890 if block.stmts.is_empty() {
891 if let Some(ref expr) = block.expr {
904 pub fn opt_def_id(def: Def) -> Option<DefId> {
910 Def::VariantCtor(id, ..) |
913 Def::AssociatedTy(id) |
917 Def::StructCtor(id, ..) |
920 Def::TraitAlias(id) |
923 Def::AssociatedConst(id) |
925 Def::Existential(id) |
926 Def::AssociatedExistential(id) |
930 Def::Upvar(..) | Def::Local(_) | Def::Label(..) | Def::PrimTy(..) | Def::SelfTy(..) |
931 Def::ToolMod | Def::NonMacroAttr{..} | Def::Err => None,
935 pub fn is_self(slf: &Arg) -> bool {
936 if let PatKind::Binding(_, _, name, _) = slf.pat.node {
937 name.name == keywords::SelfValue.name()
943 pub fn is_self_ty(slf: &hir::Ty) -> bool {
945 if let TyKind::Path(ref qp) = slf.node;
946 if let QPath::Resolved(None, ref path) = *qp;
947 if let Def::SelfTy(..) = path.def;
955 pub fn iter_input_pats<'tcx>(decl: &FnDecl, body: &'tcx Body) -> impl Iterator<Item = &'tcx Arg> {
956 (0..decl.inputs.len()).map(move |i| &body.arguments[i])
959 /// Check if a given expression is a match expression
960 /// expanded from `?` operator or `try` macro.
961 pub fn is_try(expr: &Expr) -> Option<&Expr> {
962 fn is_ok(arm: &Arm) -> bool {
964 if let PatKind::TupleStruct(ref path, ref pat, None) = arm.pats[0].node;
965 if match_qpath(path, &paths::RESULT_OK[1..]);
966 if let PatKind::Binding(_, defid, _, None) = pat[0].node;
967 if let ExprKind::Path(QPath::Resolved(None, ref path)) = arm.body.node;
968 if let Def::Local(lid) = path.def;
977 fn is_err(arm: &Arm) -> bool {
978 if let PatKind::TupleStruct(ref path, _, _) = arm.pats[0].node {
979 match_qpath(path, &paths::RESULT_ERR[1..])
985 if let ExprKind::Match(_, ref arms, ref source) = expr.node {
986 // desugared from a `?` operator
987 if let MatchSource::TryDesugar = *source {
993 if arms[0].pats.len() == 1 && arms[0].guard.is_none();
994 if arms[1].pats.len() == 1 && arms[1].guard.is_none();
995 if (is_ok(&arms[0]) && is_err(&arms[1])) ||
996 (is_ok(&arms[1]) && is_err(&arms[0]));
1006 /// Returns true if the lint is allowed in the current context
1008 /// Useful for skipping long running code when it's unnecessary
1009 pub fn is_allowed(cx: &LateContext<'_, '_>, lint: &'static Lint, id: NodeId) -> bool {
1010 cx.tcx.lint_level_at_node(lint, id).0 == Level::Allow
1013 pub fn get_arg_name(pat: &Pat) -> Option<ast::Name> {
1015 PatKind::Binding(_, _, ident, None) => Some(ident.name),
1016 PatKind::Ref(ref subpat, _) => get_arg_name(subpat),
1021 pub fn int_bits(tcx: TyCtxt<'_, '_, '_>, ity: ast::IntTy) -> u64 {
1022 layout::Integer::from_attr(&tcx, attr::IntType::SignedInt(ity)).size().bits()
1025 #[allow(clippy::cast_possible_wrap)]
1026 /// Turn a constant int byte representation into an i128
1027 pub fn sext(tcx: TyCtxt<'_, '_, '_>, u: u128, ity: ast::IntTy) -> i128 {
1028 let amt = 128 - int_bits(tcx, ity);
1029 ((u as i128) << amt) >> amt
1032 #[allow(clippy::cast_sign_loss)]
1033 /// clip unused bytes
1034 pub fn unsext(tcx: TyCtxt<'_, '_, '_>, u: i128, ity: ast::IntTy) -> u128 {
1035 let amt = 128 - int_bits(tcx, ity);
1036 ((u as u128) << amt) >> amt
1039 /// clip unused bytes
1040 pub fn clip(tcx: TyCtxt<'_, '_, '_>, u: u128, ity: ast::UintTy) -> u128 {
1041 let bits = layout::Integer::from_attr(&tcx, attr::IntType::UnsignedInt(ity)).size().bits();
1042 let amt = 128 - bits;
1046 /// Remove block comments from the given Vec of lines
1051 /// without_block_comments(vec!["/*", "foo", "*/"]);
1054 /// without_block_comments(vec!["bar", "/*", "foo", "*/"]);
1055 /// // => vec!["bar"]
1057 pub fn without_block_comments(lines: Vec<&str>) -> Vec<&str> {
1058 let mut without = vec![];
1060 let mut nest_level = 0;
1063 if line.contains("/*") {
1066 } else if line.contains("*/") {
1071 if nest_level == 0 {
1079 pub fn any_parent_is_automatically_derived(tcx: TyCtxt<'_, '_, '_>, node: NodeId) -> bool {
1081 let mut prev_enclosing_node = None;
1082 let mut enclosing_node = node;
1083 while Some(enclosing_node) != prev_enclosing_node {
1084 if is_automatically_derived(map.attrs(enclosing_node)) {
1087 prev_enclosing_node = Some(enclosing_node);
1088 enclosing_node = map.get_parent(enclosing_node);
1095 use super::{trim_multiline, without_block_comments};
1098 fn test_trim_multiline_single_line() {
1099 assert_eq!("", trim_multiline("".into(), false));
1100 assert_eq!("...", trim_multiline("...".into(), false));
1101 assert_eq!("...", trim_multiline(" ...".into(), false));
1102 assert_eq!("...", trim_multiline("\t...".into(), false));
1103 assert_eq!("...", trim_multiline("\t\t...".into(), false));
1108 fn test_trim_multiline_block() {
1114 }", trim_multiline(" if x {
1124 }", trim_multiline(" if x {
1133 fn test_trim_multiline_empty_line() {
1140 }", trim_multiline(" if x {
1149 fn test_without_block_comments_lines_without_block_comments() {
1150 let result = without_block_comments(vec!["/*", "", "*/"]);
1151 println!("result: {:?}", result);
1152 assert!(result.is_empty());
1154 let result = without_block_comments(vec!["", "/*", "", "*/", "#[crate_type = \"lib\"]", "/*", "", "*/", ""]);
1155 assert_eq!(result, vec!["", "#[crate_type = \"lib\"]", ""]);
1157 let result = without_block_comments(vec!["/* rust", "", "*/"]);
1158 assert!(result.is_empty());
1160 let result = without_block_comments(vec!["/* one-line comment */"]);
1161 assert!(result.is_empty());
1163 let result = without_block_comments(vec!["/* nested", "/* multi-line", "comment", "*/", "test", "*/"]);
1164 assert!(result.is_empty());
1166 let result = without_block_comments(vec!["/* nested /* inline /* comment */ test */ */"]);
1167 assert!(result.is_empty());
1169 let result = without_block_comments(vec!["foo", "bar", "baz"]);
1170 assert_eq!(result, vec!["foo", "bar", "baz"]);