1 use crate::{LateContext, LateLintPass, LintContext};
2 use rustc_errors::{fluent, Applicability};
4 use rustc_hir::def::Res;
5 use rustc_hir::{GenericArg, PathSegment, QPath, TyKind};
7 use rustc_span::symbol::sym;
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,
16 "pass by reference of a type flagged as `#[rustc_pass_by_value]`",
17 report_in_external_macro: true
20 declare_lint_pass!(PassByValue => [PASS_BY_VALUE]);
22 impl<'tcx> LateLintPass<'tcx> for PassByValue {
23 fn check_ty(&mut self, cx: &LateContext<'_>, ty: &'tcx hir::Ty<'tcx>) {
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() {
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(fluent::lint::pass_by_value)
34 .set_arg("ty", t.clone())
37 fluent::lint::suggestion,
39 // Changing type of function argument
40 Applicability::MaybeIncorrect,
51 fn path_for_pass_by_value(cx: &LateContext<'_>, ty: &hir::Ty<'_>) -> Option<String> {
52 if let TyKind::Path(QPath::Resolved(_, path)) = &ty.kind {
54 Res::Def(_, def_id) if cx.tcx.has_attr(def_id, sym::rustc_pass_by_value) => {
55 let name = cx.tcx.item_name(def_id).to_ident_string();
56 let path_segment = path.segments.last().unwrap();
57 return Some(format!("{}{}", name, gen_args(cx, path_segment)));
59 Res::SelfTy { trait_: None, alias_to: Some((did, _)) } => {
60 if let ty::Adt(adt, substs) = cx.tcx.type_of(did).kind() {
61 if cx.tcx.has_attr(adt.did(), sym::rustc_pass_by_value) {
62 return Some(cx.tcx.def_path_str_with_substs(adt.did(), substs));
73 fn gen_args(cx: &LateContext<'_>, segment: &PathSegment<'_>) -> String {
74 if let Some(args) = &segment.args {
78 .map(|arg| match arg {
79 GenericArg::Lifetime(lt) => lt.name.ident().to_string(),
80 GenericArg::Type(ty) => {
81 cx.tcx.sess.source_map().span_to_snippet(ty.span).unwrap_or_else(|_| "_".into())
83 GenericArg::Const(c) => {
84 cx.tcx.sess.source_map().span_to_snippet(c.span).unwrap_or_else(|_| "_".into())
86 GenericArg::Infer(_) => String::from("_"),
90 if !params.is_empty() {
91 return format!("<{}>", params.join(", "));