1 use crate::reexport::*;
2 use if_chain::if_chain;
5 use rustc::hir::def::Def;
6 use rustc::hir::def_id::{DefId, CRATE_DEF_INDEX};
7 use rustc::hir::intravisit::{NestedVisitorMap, Visitor};
10 use rustc::lint::{LateContext, Level, Lint, LintContext};
11 use rustc::session::Session;
15 layout::{self, IntegerExt},
19 use rustc_data_structures::sync::Lrc;
20 use rustc_errors::{Applicability, CodeSuggestion, Substitution, SubstitutionPart};
24 use std::str::FromStr;
25 use syntax::ast::{self, LitKind};
27 use syntax::errors::DiagnosticBuilder;
28 use syntax::source_map::{Span, DUMMY_SP};
30 use syntax::symbol::{keywords, Symbol};
40 pub mod internal_lints;
45 pub use self::hir_utils::{SpanlessEq, SpanlessHash};
49 /// Returns true if the two spans come from differing expansions (i.e. one is
50 /// from a macro and one
52 pub fn differing_macro_contexts(lhs: Span, rhs: Span) -> bool {
53 rhs.ctxt() != lhs.ctxt()
56 /// Returns `true` if the given `NodeId` is inside a constant context
61 /// if in_constant(cx, expr.id) {
65 pub fn in_constant(cx: &LateContext<'_, '_>, id: NodeId) -> bool {
66 let parent_id = cx.tcx.hir().get_parent(id);
67 match cx.tcx.hir().get(parent_id) {
69 node: ItemKind::Const(..),
72 | Node::TraitItem(&TraitItem {
73 node: TraitItemKind::Const(..),
76 | Node::ImplItem(&ImplItem {
77 node: ImplItemKind::Const(..),
82 node: ItemKind::Static(..),
89 /// Returns true if this `expn_info` was expanded by any macro.
90 pub fn in_macro(span: Span) -> bool {
91 span.ctxt().outer().expn_info().is_some()
94 /// Used to store the absolute path to a type.
96 /// See `match_def_path` for usage.
98 pub struct AbsolutePathBuffer {
99 pub names: Vec<symbol::LocalInternedString>,
102 impl ty::item_path::ItemPathBuffer for AbsolutePathBuffer {
103 fn root_mode(&self) -> &ty::item_path::RootMode {
104 const ABSOLUTE: &ty::item_path::RootMode = &ty::item_path::RootMode::Absolute;
108 fn push(&mut self, text: &str) {
109 self.names.push(symbol::Symbol::intern(text).as_str());
113 /// Check if a `DefId`'s path matches the given absolute type path usage.
117 /// match_def_path(cx.tcx, id, &["core", "option", "Option"])
120 /// See also the `paths` module.
121 pub fn match_def_path(tcx: TyCtxt<'_, '_, '_>, def_id: DefId, path: &[&str]) -> bool {
122 let mut apb = AbsolutePathBuffer { names: vec![] };
124 tcx.push_item_path(&mut apb, def_id, false);
126 apb.names.len() == path.len() && apb.names.into_iter().zip(path.iter()).all(|(a, &b)| *a == *b)
129 /// Check if type is struct, enum or union type with given def path.
130 pub fn match_type(cx: &LateContext<'_, '_>, ty: Ty<'_>, path: &[&str]) -> bool {
132 ty::Adt(adt, _) => match_def_path(cx.tcx, adt.did, path),
137 /// Check if the method call given in `expr` belongs to given trait.
138 pub fn match_trait_method(cx: &LateContext<'_, '_>, expr: &Expr, path: &[&str]) -> bool {
139 let method_call = cx.tables.type_dependent_defs()[expr.hir_id];
140 let trt_id = cx.tcx.trait_of_item(method_call.def_id());
141 if let Some(trt_id) = trt_id {
142 match_def_path(cx.tcx, trt_id, path)
148 /// Check if an expression references a variable of the given name.
149 pub fn match_var(expr: &Expr, var: Name) -> bool {
150 if let ExprKind::Path(QPath::Resolved(None, ref path)) = expr.node {
151 if path.segments.len() == 1 && path.segments[0].ident.name == var {
158 pub fn last_path_segment(path: &QPath) -> &PathSegment {
160 QPath::Resolved(_, ref path) => path.segments.last().expect("A path must have at least one segment"),
161 QPath::TypeRelative(_, ref seg) => seg,
165 pub fn single_segment_path(path: &QPath) -> Option<&PathSegment> {
167 QPath::Resolved(_, ref path) if path.segments.len() == 1 => Some(&path.segments[0]),
168 QPath::Resolved(..) => None,
169 QPath::TypeRelative(_, ref seg) => Some(seg),
173 /// Match a `Path` against a slice of segment string literals.
177 /// match_qpath(path, &["std", "rt", "begin_unwind"])
179 pub fn match_qpath(path: &QPath, segments: &[&str]) -> bool {
181 QPath::Resolved(_, ref path) => match_path(path, segments),
182 QPath::TypeRelative(ref ty, ref segment) => match ty.node {
183 TyKind::Path(ref inner_path) => {
185 && match_qpath(inner_path, &segments[..(segments.len() - 1)])
186 && segment.ident.name == segments[segments.len() - 1]
193 pub fn match_path(path: &Path, segments: &[&str]) -> bool {
197 .zip(segments.iter().rev())
198 .all(|(a, b)| a.ident.name == *b)
201 /// Match a `Path` against a slice of segment string literals, e.g.
205 /// match_qpath(path, &["std", "rt", "begin_unwind"])
207 pub fn match_path_ast(path: &ast::Path, segments: &[&str]) -> bool {
211 .zip(segments.iter().rev())
212 .all(|(a, b)| a.ident.name == *b)
215 /// Get the definition associated to a path.
216 pub fn path_to_def(cx: &LateContext<'_, '_>, path: &[&str]) -> Option<def::Def> {
217 let crates = cx.tcx.crates();
218 let krate = crates.iter().find(|&&krate| cx.tcx.crate_name(krate) == path[0]);
219 if let Some(krate) = krate {
222 index: CRATE_DEF_INDEX,
224 let mut items = cx.tcx.item_children(krate);
225 let mut path_it = path.iter().skip(1).peekable();
228 let segment = match path_it.next() {
229 Some(segment) => segment,
233 for item in mem::replace(&mut items, Lrc::new(vec![])).iter() {
234 if item.ident.name == *segment {
235 if path_it.peek().is_none() {
236 return Some(item.def);
239 items = cx.tcx.item_children(item.def.def_id());
249 /// Convenience function to get the `DefId` of a trait by path.
250 pub fn get_trait_def_id(cx: &LateContext<'_, '_>, path: &[&str]) -> Option<DefId> {
251 let def = match path_to_def(cx, path) {
257 def::Def::Trait(trait_id) => Some(trait_id),
262 /// Check whether a type implements a trait.
263 /// See also `get_trait_def_id`.
264 pub fn implements_trait<'a, 'tcx>(
265 cx: &LateContext<'a, 'tcx>,
268 ty_params: &[Kind<'tcx>],
270 let ty = cx.tcx.erase_regions(&ty);
271 let obligation = cx.tcx.predicate_for_trait_def(
273 traits::ObligationCause::dummy(),
281 .enter(|infcx| infcx.predicate_must_hold_modulo_regions(&obligation))
284 /// Check whether this type implements Drop.
285 pub fn has_drop<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, ty: Ty<'tcx>) -> bool {
286 match ty.ty_adt_def() {
287 Some(def) => def.has_dtor(cx.tcx),
292 /// Resolve the definition of a node from its `HirId`.
293 pub fn resolve_node(cx: &LateContext<'_, '_>, qpath: &QPath, id: HirId) -> def::Def {
294 cx.tables.qpath_def(qpath, id)
297 /// Return the method names and argument list of nested method call expressions that make up
299 pub fn method_calls<'a>(expr: &'a Expr, max_depth: usize) -> (Vec<Symbol>, Vec<&'a [Expr]>) {
300 let mut method_names = Vec::with_capacity(max_depth);
301 let mut arg_lists = Vec::with_capacity(max_depth);
303 let mut current = expr;
304 for _ in 0..max_depth {
305 if let ExprKind::MethodCall(path, _, args) = ¤t.node {
306 if args.iter().any(|e| in_macro(e.span)) {
309 method_names.push(path.ident.name);
310 arg_lists.push(&**args);
317 (method_names, arg_lists)
320 /// Match an `Expr` against a chain of methods, and return the matched `Expr`s.
322 /// For example, if `expr` represents the `.baz()` in `foo.bar().baz()`,
323 /// `matched_method_chain(expr, &["bar", "baz"])` will return a `Vec`
324 /// containing the `Expr`s for
325 /// `.bar()` and `.baz()`
326 pub fn method_chain_args<'a>(expr: &'a Expr, methods: &[&str]) -> Option<Vec<&'a [Expr]>> {
327 let mut current = expr;
328 let mut matched = Vec::with_capacity(methods.len());
329 for method_name in methods.iter().rev() {
330 // method chains are stored last -> first
331 if let ExprKind::MethodCall(ref path, _, ref args) = current.node {
332 if path.ident.name == *method_name {
333 if args.iter().any(|e| in_macro(e.span)) {
336 matched.push(&**args); // build up `matched` backwards
337 current = &args[0] // go to parent expression
345 matched.reverse(); // reverse `matched`, so that it is in the same order as `methods`
349 /// Get the name of the item the expression is in, if available.
350 pub fn get_item_name(cx: &LateContext<'_, '_>, expr: &Expr) -> Option<Name> {
351 let parent_id = cx.tcx.hir().get_parent(expr.id);
352 match cx.tcx.hir().find(parent_id) {
353 Some(Node::Item(&Item { ref ident, .. })) => Some(ident.name),
354 Some(Node::TraitItem(&TraitItem { ident, .. })) | Some(Node::ImplItem(&ImplItem { ident, .. })) => {
361 /// Get the name of a `Pat`, if any
362 pub fn get_pat_name(pat: &Pat) -> Option<Name> {
364 PatKind::Binding(_, _, ref spname, _) => Some(spname.name),
365 PatKind::Path(ref qpath) => single_segment_path(qpath).map(|ps| ps.ident.name),
366 PatKind::Box(ref p) | PatKind::Ref(ref p, _) => get_pat_name(&*p),
371 struct ContainsName {
376 impl<'tcx> Visitor<'tcx> for ContainsName {
377 fn visit_name(&mut self, _: Span, name: Name) {
378 if self.name == name {
382 fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'tcx> {
383 NestedVisitorMap::None
387 /// check if an `Expr` contains a certain name
388 pub fn contains_name(name: Name, expr: &Expr) -> bool {
389 let mut cn = ContainsName { name, result: false };
394 /// Convert a span to a code snippet if available, otherwise use default.
396 /// This is useful if you want to provide suggestions for your lint or more generally, if you want
397 /// to convert a given `Span` to a `str`.
401 /// snippet(cx, expr.span, "..")
403 pub fn snippet<'a, 'b, T: LintContext<'b>>(cx: &T, span: Span, default: &'a str) -> Cow<'a, str> {
404 snippet_opt(cx, span).map_or_else(|| Cow::Borrowed(default), From::from)
407 /// Same as `snippet`, but it adapts the applicability level by following rules:
409 /// - Applicability level `Unspecified` will never be changed.
410 /// - If the span is inside a macro, change the applicability level to `MaybeIncorrect`.
411 /// - If the default value is used and the applicability level is `MachineApplicable`, change it to
412 /// `HasPlaceholders`
413 pub fn snippet_with_applicability<'a, 'b, T: LintContext<'b>>(
417 applicability: &mut Applicability,
419 if *applicability != Applicability::Unspecified && in_macro(span) {
420 *applicability = Applicability::MaybeIncorrect;
422 snippet_opt(cx, span).map_or_else(
424 if *applicability == Applicability::MachineApplicable {
425 *applicability = Applicability::HasPlaceholders;
427 Cow::Borrowed(default)
433 /// Same as `snippet`, but should only be used when it's clear that the input span is
434 /// not a macro argument.
435 pub fn snippet_with_macro_callsite<'a, 'b, T: LintContext<'b>>(cx: &T, span: Span, default: &'a str) -> Cow<'a, str> {
436 snippet(cx, span.source_callsite(), default)
439 /// Convert a span to a code snippet. Returns `None` if not available.
440 pub fn snippet_opt<'a, T: LintContext<'a>>(cx: &T, span: Span) -> Option<String> {
441 cx.sess().source_map().span_to_snippet(span).ok()
444 /// Convert a span (from a block) to a code snippet if available, otherwise use
446 /// This trims the code of indentation, except for the first line. Use it for
447 /// blocks or block-like
448 /// things which need to be printed as such.
452 /// snippet_block(cx, expr.span, "..")
454 pub fn snippet_block<'a, 'b, T: LintContext<'b>>(cx: &T, span: Span, default: &'a str) -> Cow<'a, str> {
455 let snip = snippet(cx, span, default);
456 trim_multiline(snip, true)
459 /// Same as `snippet_block`, but adapts the applicability level by the rules of
460 /// `snippet_with_applicabiliy`.
461 pub fn snippet_block_with_applicability<'a, 'b, T: LintContext<'b>>(
465 applicability: &mut Applicability,
467 let snip = snippet_with_applicability(cx, span, default, applicability);
468 trim_multiline(snip, true)
471 /// Returns a new Span that covers the full last line of the given Span
472 pub fn last_line_of_span<'a, T: LintContext<'a>>(cx: &T, span: Span) -> Span {
473 let source_map_and_line = cx.sess().source_map().lookup_line(span.lo()).unwrap();
474 let line_no = source_map_and_line.line;
475 let line_start = &source_map_and_line.sf.lines[line_no];
476 Span::new(*line_start, span.hi(), span.ctxt())
479 /// Like `snippet_block`, but add braces if the expr is not an `ExprKind::Block`.
480 /// Also takes an `Option<String>` which can be put inside the braces.
481 pub fn expr_block<'a, 'b, T: LintContext<'b>>(
484 option: Option<String>,
487 let code = snippet_block(cx, expr.span, default);
488 let string = option.unwrap_or_default();
489 if in_macro(expr.span) {
490 Cow::Owned(format!("{{ {} }}", snippet_with_macro_callsite(cx, expr.span, default)))
491 } else if let ExprKind::Block(_, _) = expr.node {
492 Cow::Owned(format!("{}{}", code, string))
493 } else if string.is_empty() {
494 Cow::Owned(format!("{{ {} }}", code))
496 Cow::Owned(format!("{{\n{};\n{}\n}}", code, string))
500 /// Trim indentation from a multiline string with possibility of ignoring the
502 pub fn trim_multiline(s: Cow<'_, str>, ignore_first: bool) -> Cow<'_, str> {
503 let s_space = trim_multiline_inner(s, ignore_first, ' ');
504 let s_tab = trim_multiline_inner(s_space, ignore_first, '\t');
505 trim_multiline_inner(s_tab, ignore_first, ' ')
508 fn trim_multiline_inner(s: Cow<'_, str>, ignore_first: bool, ch: char) -> Cow<'_, str> {
511 .skip(ignore_first as usize)
516 // ignore empty lines
517 Some(l.char_indices().find(|&(_, x)| x != ch).unwrap_or((l.len(), ch)).0)
527 if (ignore_first && i == 0) || l.is_empty() {
541 /// Get a parent expressions if any – this is useful to constrain a lint.
542 pub fn get_parent_expr<'c>(cx: &'c LateContext<'_, '_>, e: &Expr) -> Option<&'c Expr> {
543 let map = &cx.tcx.hir();
544 let node_id: NodeId = e.id;
545 let parent_id: NodeId = map.get_parent_node(node_id);
546 if node_id == parent_id {
549 map.find(parent_id).and_then(|node| {
550 if let Node::Expr(parent) = node {
558 pub fn get_enclosing_block<'a, 'tcx: 'a>(cx: &LateContext<'a, 'tcx>, node: NodeId) -> Option<&'tcx Block> {
559 let map = &cx.tcx.hir();
560 let enclosing_node = map
561 .get_enclosing_scope(node)
562 .and_then(|enclosing_id| map.find(enclosing_id));
563 if let Some(node) = enclosing_node {
565 Node::Block(block) => Some(block),
567 node: ItemKind::Fn(_, _, _, eid),
570 | Node::ImplItem(&ImplItem {
571 node: ImplItemKind::Method(_, eid),
573 }) => match cx.tcx.hir().body(eid).value.node {
574 ExprKind::Block(ref block, _) => Some(block),
584 pub struct DiagnosticWrapper<'a>(pub DiagnosticBuilder<'a>);
586 impl<'a> Drop for DiagnosticWrapper<'a> {
592 impl<'a> DiagnosticWrapper<'a> {
593 fn docs_link(&mut self, lint: &'static Lint) {
594 if env::var("CLIPPY_DISABLE_DOCS_LINKS").is_err() {
595 self.0.help(&format!(
596 "for further information visit https://rust-lang.github.io/rust-clippy/{}/index.html#{}",
597 &option_env!("RUST_RELEASE_NUM").map_or("master".to_string(), |n| {
598 // extract just major + minor version and ignore patch versions
599 format!("rust-{}", n.rsplitn(2, '.').nth(1).unwrap())
601 lint.name_lower().replacen("clippy::", "", 1)
607 pub fn span_lint<'a, T: LintContext<'a>>(cx: &T, lint: &'static Lint, sp: Span, msg: &str) {
608 DiagnosticWrapper(cx.struct_span_lint(lint, sp, msg)).docs_link(lint);
611 pub fn span_help_and_lint<'a, 'tcx: 'a, T: LintContext<'tcx>>(
618 let mut db = DiagnosticWrapper(cx.struct_span_lint(lint, span, msg));
623 pub fn span_note_and_lint<'a, 'tcx: 'a, T: LintContext<'tcx>>(
631 let mut db = DiagnosticWrapper(cx.struct_span_lint(lint, span, msg));
632 if note_span == span {
635 db.0.span_note(note_span, note);
640 pub fn span_lint_and_then<'a, 'tcx: 'a, T: LintContext<'tcx>, F>(
647 F: for<'b> FnOnce(&mut DiagnosticBuilder<'b>),
649 let mut db = DiagnosticWrapper(cx.struct_span_lint(lint, sp, msg));
654 pub fn span_lint_node(cx: &LateContext<'_, '_>, lint: &'static Lint, node: NodeId, sp: Span, msg: &str) {
655 DiagnosticWrapper(cx.tcx.struct_span_lint_node(lint, node, sp, msg)).docs_link(lint);
658 pub fn span_lint_node_and_then(
659 cx: &LateContext<'_, '_>,
664 f: impl FnOnce(&mut DiagnosticBuilder<'_>),
666 let mut db = DiagnosticWrapper(cx.tcx.struct_span_lint_node(lint, node, sp, msg));
671 /// Add a span lint with a suggestion on how to fix it.
673 /// These suggestions can be parsed by rustfix to allow it to automatically fix your code.
674 /// In the example below, `help` is `"try"` and `sugg` is the suggested replacement `".any(|x| x >
678 /// error: This `.fold` can be more succinctly expressed as `.any`
679 /// --> $DIR/methods.rs:390:13
681 /// 390 | let _ = (0..3).fold(false, |acc, x| acc || x > 2);
682 /// | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: try: `.any(|x| x > 2)`
684 /// = note: `-D fold-any` implied by `-D warnings`
686 pub fn span_lint_and_sugg<'a, 'tcx: 'a, T: LintContext<'tcx>>(
693 applicability: Applicability,
695 span_lint_and_then(cx, lint, sp, msg, |db| {
696 db.span_suggestion_with_applicability(sp, help, sugg, applicability);
700 /// Create a suggestion made from several `span → replacement`.
702 /// Note: in the JSON format (used by `compiletest_rs`), the help message will
704 /// replacement. In human-readable format though, it only appears once before
705 /// the whole suggestion.
706 pub fn multispan_sugg<I>(db: &mut DiagnosticBuilder<'_>, help_msg: String, sugg: I)
708 I: IntoIterator<Item = (Span, String)>,
710 let sugg = CodeSuggestion {
711 substitutions: vec![Substitution {
714 .map(|(span, snippet)| SubstitutionPart { snippet, span })
718 show_code_when_inline: true,
719 applicability: Applicability::Unspecified,
721 db.suggestions.push(sugg);
724 /// Return the base type for HIR references and pointers.
725 pub fn walk_ptrs_hir_ty(ty: &hir::Ty) -> &hir::Ty {
727 TyKind::Ptr(ref mut_ty) | TyKind::Rptr(_, ref mut_ty) => walk_ptrs_hir_ty(&mut_ty.ty),
732 /// Return the base type for references and raw pointers.
733 pub fn walk_ptrs_ty(ty: Ty<'_>) -> Ty<'_> {
735 ty::Ref(_, ty, _) => walk_ptrs_ty(ty),
740 /// Return the base type for references and raw pointers, and count reference
742 pub fn walk_ptrs_ty_depth(ty: Ty<'_>) -> (Ty<'_>, usize) {
743 fn inner(ty: Ty<'_>, depth: usize) -> (Ty<'_>, usize) {
745 ty::Ref(_, ty, _) => inner(ty, depth + 1),
752 /// Check whether the given expression is a constant literal of the given value.
753 pub fn is_integer_literal(expr: &Expr, value: u128) -> bool {
754 // FIXME: use constant folding
755 if let ExprKind::Lit(ref spanned) = expr.node {
756 if let LitKind::Int(v, _) = spanned.node {
763 /// Returns `true` if the given `Expr` has been coerced before.
765 /// Examples of coercions can be found in the Nomicon at
766 /// <https://doc.rust-lang.org/nomicon/coercions.html>.
768 /// See `rustc::ty::adjustment::Adjustment` and `rustc_typeck::check::coercion` for more
769 /// information on adjustments and coercions.
770 pub fn is_adjusted(cx: &LateContext<'_, '_>, e: &Expr) -> bool {
771 cx.tables.adjustments().get(e.hir_id).is_some()
774 pub struct LimitStack {
778 impl Drop for LimitStack {
780 assert_eq!(self.stack.len(), 1);
785 pub fn new(limit: u64) -> Self {
786 Self { stack: vec![limit] }
788 pub fn limit(&self) -> u64 {
789 *self.stack.last().expect("there should always be a value in the stack")
791 pub fn push_attrs(&mut self, sess: &Session, attrs: &[ast::Attribute], name: &'static str) {
792 let stack = &mut self.stack;
793 parse_attrs(sess, attrs, name, |val| stack.push(val));
795 pub fn pop_attrs(&mut self, sess: &Session, attrs: &[ast::Attribute], name: &'static str) {
796 let stack = &mut self.stack;
797 parse_attrs(sess, attrs, name, |val| assert_eq!(stack.pop(), Some(val)));
801 pub fn get_attr<'a>(attrs: &'a [ast::Attribute], name: &'static str) -> impl Iterator<Item = &'a ast::Attribute> {
802 attrs.iter().filter(move |attr| {
803 attr.path.segments.len() == 2
804 && attr.path.segments[0].ident.to_string() == "clippy"
805 && attr.path.segments[1].ident.to_string() == name
809 fn parse_attrs<F: FnMut(u64)>(sess: &Session, attrs: &[ast::Attribute], name: &'static str, mut f: F) {
810 for attr in get_attr(attrs, name) {
811 if let Some(ref value) = attr.value_str() {
812 if let Ok(value) = FromStr::from_str(&value.as_str()) {
815 sess.span_err(attr.span, "not a number");
818 sess.span_err(attr.span, "bad clippy attribute");
823 /// Return the pre-expansion span if is this comes from an expansion of the
825 /// See also `is_direct_expn_of`.
826 pub fn is_expn_of(mut span: Span, name: &str) -> Option<Span> {
828 let span_name_span = span
832 .map(|ei| (ei.format.name(), ei.call_site));
834 match span_name_span {
835 Some((mac_name, new_span)) if mac_name == name => return Some(new_span),
837 Some((_, new_span)) => span = new_span,
842 /// Return the pre-expansion span if is this directly comes from an expansion
843 /// of the macro `name`.
844 /// The difference with `is_expn_of` is that in
848 /// `42` is considered expanded from `foo!` and `bar!` by `is_expn_of` but only
850 /// `is_direct_expn_of`.
851 pub fn is_direct_expn_of(span: Span, name: &str) -> Option<Span> {
852 let span_name_span = span
856 .map(|ei| (ei.format.name(), ei.call_site));
858 match span_name_span {
859 Some((mac_name, new_span)) if mac_name == name => Some(new_span),
864 /// Convenience function to get the return type of a function
865 pub fn return_ty<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, fn_item: NodeId) -> Ty<'tcx> {
866 let fn_def_id = cx.tcx.hir().local_def_id(fn_item);
867 let ret_ty = cx.tcx.fn_sig(fn_def_id).output();
868 cx.tcx.erase_late_bound_regions(&ret_ty)
871 /// Check if two types are the same.
873 /// This discards any lifetime annotations, too.
874 // FIXME: this works correctly for lifetimes bounds (`for <'a> Foo<'a>` == `for
876 // not for type parameters.
877 pub fn same_tys<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, a: Ty<'tcx>, b: Ty<'tcx>) -> bool {
878 let a = cx.tcx.erase_late_bound_regions(&Binder::bind(a));
879 let b = cx.tcx.erase_late_bound_regions(&Binder::bind(b));
882 .enter(|infcx| infcx.can_eq(cx.param_env, a, b).is_ok())
885 /// Return whether the given type is an `unsafe` function.
886 pub fn type_is_unsafe_function<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, ty: Ty<'tcx>) -> bool {
888 ty::FnDef(..) | ty::FnPtr(_) => ty.fn_sig(cx.tcx).unsafety() == Unsafety::Unsafe,
893 pub fn is_copy<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, ty: Ty<'tcx>) -> bool {
894 ty.is_copy_modulo_regions(cx.tcx.global_tcx(), cx.param_env, DUMMY_SP)
897 /// Return whether a pattern is refutable.
898 pub fn is_refutable(cx: &LateContext<'_, '_>, pat: &Pat) -> bool {
899 fn is_enum_variant(cx: &LateContext<'_, '_>, qpath: &QPath, id: HirId) -> bool {
901 cx.tables.qpath_def(qpath, id),
902 def::Def::Variant(..) | def::Def::VariantCtor(..)
906 fn are_refutable<'a, I: Iterator<Item = &'a Pat>>(cx: &LateContext<'_, '_>, mut i: I) -> bool {
907 i.any(|pat| is_refutable(cx, pat))
911 PatKind::Binding(..) | PatKind::Wild => false,
912 PatKind::Box(ref pat) | PatKind::Ref(ref pat, _) => is_refutable(cx, pat),
913 PatKind::Lit(..) | PatKind::Range(..) => true,
914 PatKind::Path(ref qpath) => is_enum_variant(cx, qpath, pat.hir_id),
915 PatKind::Tuple(ref pats, _) => are_refutable(cx, pats.iter().map(|pat| &**pat)),
916 PatKind::Struct(ref qpath, ref fields, _) => {
917 if is_enum_variant(cx, qpath, pat.hir_id) {
920 are_refutable(cx, fields.iter().map(|field| &*field.node.pat))
923 PatKind::TupleStruct(ref qpath, ref pats, _) => {
924 if is_enum_variant(cx, qpath, pat.hir_id) {
927 are_refutable(cx, pats.iter().map(|pat| &**pat))
930 PatKind::Slice(ref head, ref middle, ref tail) => {
931 are_refutable(cx, head.iter().chain(middle).chain(tail.iter()).map(|pat| &**pat))
936 /// Checks for the `#[automatically_derived]` attribute all `#[derive]`d
937 /// implementations have.
938 pub fn is_automatically_derived(attrs: &[ast::Attribute]) -> bool {
939 attr::contains_name(attrs, "automatically_derived")
942 /// Remove blocks around an expression.
944 /// Ie. `x`, `{ x }` and `{{{{ x }}}}` all give `x`. `{ x; y }` and `{}` return
946 pub fn remove_blocks(expr: &Expr) -> &Expr {
947 if let ExprKind::Block(ref block, _) = expr.node {
948 if block.stmts.is_empty() {
949 if let Some(ref expr) = block.expr {
962 pub fn opt_def_id(def: Def) -> Option<DefId> {
968 | Def::VariantCtor(id, ..)
971 | Def::AssociatedTy(id)
975 | Def::StructCtor(id, ..)
978 | Def::TraitAlias(id)
981 | Def::AssociatedConst(id)
983 | Def::Existential(id)
984 | Def::AssociatedExistential(id)
985 | Def::SelfCtor(id) => Some(id),
993 | Def::NonMacroAttr { .. }
998 pub fn is_self(slf: &Arg) -> bool {
999 if let PatKind::Binding(_, _, name, _) = slf.pat.node {
1000 name.name == keywords::SelfLower.name()
1006 pub fn is_self_ty(slf: &hir::Ty) -> bool {
1008 if let TyKind::Path(ref qp) = slf.node;
1009 if let QPath::Resolved(None, ref path) = *qp;
1010 if let Def::SelfTy(..) = path.def;
1018 pub fn iter_input_pats<'tcx>(decl: &FnDecl, body: &'tcx Body) -> impl Iterator<Item = &'tcx Arg> {
1019 (0..decl.inputs.len()).map(move |i| &body.arguments[i])
1022 /// Check if a given expression is a match expression
1023 /// expanded from `?` operator or `try` macro.
1024 pub fn is_try(expr: &Expr) -> Option<&Expr> {
1025 fn is_ok(arm: &Arm) -> bool {
1027 if let PatKind::TupleStruct(ref path, ref pat, None) = arm.pats[0].node;
1028 if match_qpath(path, &paths::RESULT_OK[1..]);
1029 if let PatKind::Binding(_, defid, _, None) = pat[0].node;
1030 if let ExprKind::Path(QPath::Resolved(None, ref path)) = arm.body.node;
1031 if let Def::Local(lid) = path.def;
1040 fn is_err(arm: &Arm) -> bool {
1041 if let PatKind::TupleStruct(ref path, _, _) = arm.pats[0].node {
1042 match_qpath(path, &paths::RESULT_ERR[1..])
1048 if let ExprKind::Match(_, ref arms, ref source) = expr.node {
1049 // desugared from a `?` operator
1050 if let MatchSource::TryDesugar = *source {
1056 if arms[0].pats.len() == 1 && arms[0].guard.is_none();
1057 if arms[1].pats.len() == 1 && arms[1].guard.is_none();
1058 if (is_ok(&arms[0]) && is_err(&arms[1])) ||
1059 (is_ok(&arms[1]) && is_err(&arms[0]));
1069 /// Returns true if the lint is allowed in the current context
1071 /// Useful for skipping long running code when it's unnecessary
1072 pub fn is_allowed(cx: &LateContext<'_, '_>, lint: &'static Lint, id: NodeId) -> bool {
1073 cx.tcx.lint_level_at_node(lint, id).0 == Level::Allow
1076 pub fn get_arg_name(pat: &Pat) -> Option<ast::Name> {
1078 PatKind::Binding(_, _, ident, None) => Some(ident.name),
1079 PatKind::Ref(ref subpat, _) => get_arg_name(subpat),
1084 pub fn int_bits(tcx: TyCtxt<'_, '_, '_>, ity: ast::IntTy) -> u64 {
1085 layout::Integer::from_attr(&tcx, attr::IntType::SignedInt(ity))
1090 #[allow(clippy::cast_possible_wrap)]
1091 /// Turn a constant int byte representation into an i128
1092 pub fn sext(tcx: TyCtxt<'_, '_, '_>, u: u128, ity: ast::IntTy) -> i128 {
1093 let amt = 128 - int_bits(tcx, ity);
1094 ((u as i128) << amt) >> amt
1097 #[allow(clippy::cast_sign_loss)]
1098 /// clip unused bytes
1099 pub fn unsext(tcx: TyCtxt<'_, '_, '_>, u: i128, ity: ast::IntTy) -> u128 {
1100 let amt = 128 - int_bits(tcx, ity);
1101 ((u as u128) << amt) >> amt
1104 /// clip unused bytes
1105 pub fn clip(tcx: TyCtxt<'_, '_, '_>, u: u128, ity: ast::UintTy) -> u128 {
1106 let bits = layout::Integer::from_attr(&tcx, attr::IntType::UnsignedInt(ity))
1109 let amt = 128 - bits;
1113 /// Remove block comments from the given Vec of lines
1118 /// without_block_comments(vec!["/*", "foo", "*/"]);
1121 /// without_block_comments(vec!["bar", "/*", "foo", "*/"]);
1122 /// // => vec!["bar"]
1124 pub fn without_block_comments(lines: Vec<&str>) -> Vec<&str> {
1125 let mut without = vec![];
1127 let mut nest_level = 0;
1130 if line.contains("/*") {
1133 } else if line.contains("*/") {
1138 if nest_level == 0 {
1146 pub fn any_parent_is_automatically_derived(tcx: TyCtxt<'_, '_, '_>, node: NodeId) -> bool {
1147 let map = &tcx.hir();
1148 let mut prev_enclosing_node = None;
1149 let mut enclosing_node = node;
1150 while Some(enclosing_node) != prev_enclosing_node {
1151 if is_automatically_derived(map.attrs(enclosing_node)) {
1154 prev_enclosing_node = Some(enclosing_node);
1155 enclosing_node = map.get_parent(enclosing_node);
1162 use super::{trim_multiline, without_block_comments};
1165 fn test_trim_multiline_single_line() {
1166 assert_eq!("", trim_multiline("".into(), false));
1167 assert_eq!("...", trim_multiline("...".into(), false));
1168 assert_eq!("...", trim_multiline(" ...".into(), false));
1169 assert_eq!("...", trim_multiline("\t...".into(), false));
1170 assert_eq!("...", trim_multiline("\t\t...".into(), false));
1175 fn test_trim_multiline_block() {
1181 }", trim_multiline(" if x {
1191 }", trim_multiline(" if x {
1200 fn test_trim_multiline_empty_line() {
1207 }", trim_multiline(" if x {
1216 fn test_without_block_comments_lines_without_block_comments() {
1217 let result = without_block_comments(vec!["/*", "", "*/"]);
1218 println!("result: {:?}", result);
1219 assert!(result.is_empty());
1221 let result = without_block_comments(vec!["", "/*", "", "*/", "#[crate_type = \"lib\"]", "/*", "", "*/", ""]);
1222 assert_eq!(result, vec!["", "#[crate_type = \"lib\"]", ""]);
1224 let result = without_block_comments(vec!["/* rust", "", "*/"]);
1225 assert!(result.is_empty());
1227 let result = without_block_comments(vec!["/* one-line comment */"]);
1228 assert!(result.is_empty());
1230 let result = without_block_comments(vec!["/* nested", "/* multi-line", "comment", "*/", "test", "*/"]);
1231 assert!(result.is_empty());
1233 let result = without_block_comments(vec!["/* nested /* inline /* comment */ test */ */"]);
1234 assert!(result.is_empty());
1236 let result = without_block_comments(vec!["foo", "bar", "baz"]);
1237 assert_eq!(result, vec!["foo", "bar", "baz"]);