]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_lint/src/pass_by_value.rs
Document that pre-expansion lint passes are deprecated
[rust.git] / compiler / rustc_lint / src / pass_by_value.rs
1 use crate::{LateContext, LateLintPass, LintContext};
2 use rustc_errors::Applicability;
3 use rustc_hir as hir;
4 use rustc_hir::def::Res;
5 use rustc_hir::{GenericArg, PathSegment, QPath, TyKind};
6 use rustc_middle::ty;
7 use rustc_span::symbol::sym;
8
9 declare_tool_lint! {
10     /// The `rustc_pass_by_value` lint marks a type with `#[rustc_pass_by_value]` requiring it to
11     /// always be passed by value. This is usually used for types that are thin wrappers around
12     /// references, so there is no benefit to an extra layer of indirection. (Example: `Ty` which
13     /// is a reference to an `Interned<TyS>`)
14     pub rustc::PASS_BY_VALUE,
15     Warn,
16     "pass by reference of a type flagged as `#[rustc_pass_by_value]`",
17     report_in_external_macro: true
18 }
19
20 declare_lint_pass!(PassByValue => [PASS_BY_VALUE]);
21
22 impl<'tcx> LateLintPass<'tcx> for PassByValue {
23     fn check_ty(&mut self, cx: &LateContext<'_>, ty: &'tcx hir::Ty<'tcx>) {
24         match &ty.kind {
25             TyKind::Rptr(_, hir::MutTy { ty: inner_ty, mutbl: hir::Mutability::Not }) => {
26                 if let Some(impl_did) = cx.tcx.impl_of_method(ty.hir_id.owner.to_def_id()) {
27                     if cx.tcx.impl_trait_ref(impl_did).is_some() {
28                         return;
29                     }
30                 }
31                 if let Some(t) = path_for_pass_by_value(cx, &inner_ty) {
32                     cx.struct_span_lint(PASS_BY_VALUE, ty.span, |lint| {
33                         lint.build(&format!("passing `{}` by reference", t))
34                             .span_suggestion(
35                                 ty.span,
36                                 "try passing by value",
37                                 t,
38                                 // Changing type of function argument
39                                 Applicability::MaybeIncorrect,
40                             )
41                             .emit();
42                     })
43                 }
44             }
45             _ => {}
46         }
47     }
48 }
49
50 fn path_for_pass_by_value(cx: &LateContext<'_>, ty: &hir::Ty<'_>) -> Option<String> {
51     if let TyKind::Path(QPath::Resolved(_, path)) = &ty.kind {
52         match path.res {
53             Res::Def(_, def_id) if cx.tcx.has_attr(def_id, sym::rustc_pass_by_value) => {
54                 let name = cx.tcx.item_name(def_id).to_ident_string();
55                 let path_segment = path.segments.last().unwrap();
56                 return Some(format!("{}{}", name, gen_args(cx, path_segment)));
57             }
58             Res::SelfTy { trait_: None, alias_to: Some((did, _)) } => {
59                 if let ty::Adt(adt, substs) = cx.tcx.type_of(did).kind() {
60                     if cx.tcx.has_attr(adt.did, sym::rustc_pass_by_value) {
61                         return Some(cx.tcx.def_path_str_with_substs(adt.did, substs));
62                     }
63                 }
64             }
65             _ => (),
66         }
67     }
68
69     None
70 }
71
72 fn gen_args(cx: &LateContext<'_>, segment: &PathSegment<'_>) -> String {
73     if let Some(args) = &segment.args {
74         let params = args
75             .args
76             .iter()
77             .map(|arg| match arg {
78                 GenericArg::Lifetime(lt) => lt.name.ident().to_string(),
79                 GenericArg::Type(ty) => {
80                     cx.tcx.sess.source_map().span_to_snippet(ty.span).unwrap_or_else(|_| "_".into())
81                 }
82                 GenericArg::Const(c) => {
83                     cx.tcx.sess.source_map().span_to_snippet(c.span).unwrap_or_else(|_| "_".into())
84                 }
85                 GenericArg::Infer(_) => String::from("_"),
86             })
87             .collect::<Vec<_>>();
88
89         if !params.is_empty() {
90             return format!("<{}>", params.join(", "));
91         }
92     }
93
94     String::new()
95 }