]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_mir_transform/src/function_item_references.rs
Auto merge of #93081 - nikic:aarch64-fix, r=cuviper
[rust.git] / compiler / rustc_mir_transform / src / function_item_references.rs
1 use itertools::Itertools;
2 use rustc_errors::Applicability;
3 use rustc_hir::def_id::DefId;
4 use rustc_middle::mir::visit::Visitor;
5 use rustc_middle::mir::*;
6 use rustc_middle::ty::{
7     self,
8     subst::{GenericArgKind, Subst, SubstsRef},
9     PredicateKind, Ty, TyCtxt, TyS,
10 };
11 use rustc_session::lint::builtin::FUNCTION_ITEM_REFERENCES;
12 use rustc_span::{symbol::sym, Span};
13 use rustc_target::spec::abi::Abi;
14
15 use crate::MirLint;
16
17 pub struct FunctionItemReferences;
18
19 impl<'tcx> MirLint<'tcx> for FunctionItemReferences {
20     fn run_lint(&self, tcx: TyCtxt<'tcx>, body: &Body<'tcx>) {
21         let mut checker = FunctionItemRefChecker { tcx, body };
22         checker.visit_body(&body);
23     }
24 }
25
26 struct FunctionItemRefChecker<'a, 'tcx> {
27     tcx: TyCtxt<'tcx>,
28     body: &'a Body<'tcx>,
29 }
30
31 impl<'tcx> Visitor<'tcx> for FunctionItemRefChecker<'_, 'tcx> {
32     /// Emits a lint for function reference arguments bound by `fmt::Pointer` or passed to
33     /// `transmute`. This only handles arguments in calls outside macro expansions to avoid double
34     /// counting function references formatted as pointers by macros.
35     fn visit_terminator(&mut self, terminator: &Terminator<'tcx>, location: Location) {
36         if let TerminatorKind::Call {
37             func,
38             args,
39             destination: _,
40             cleanup: _,
41             from_hir_call: _,
42             fn_span: _,
43         } = &terminator.kind
44         {
45             let source_info = *self.body.source_info(location);
46             // Only handle function calls outside macros
47             if !source_info.span.from_expansion() {
48                 let func_ty = func.ty(self.body, self.tcx);
49                 if let ty::FnDef(def_id, substs_ref) = *func_ty.kind() {
50                     // Handle calls to `transmute`
51                     if self.tcx.is_diagnostic_item(sym::transmute, def_id) {
52                         let arg_ty = args[0].ty(self.body, self.tcx);
53                         for generic_inner_ty in arg_ty.walk() {
54                             if let GenericArgKind::Type(inner_ty) = generic_inner_ty.unpack() {
55                                 if let Some((fn_id, fn_substs)) =
56                                     FunctionItemRefChecker::is_fn_ref(inner_ty)
57                                 {
58                                     let span = self.nth_arg_span(&args, 0);
59                                     self.emit_lint(fn_id, fn_substs, source_info, span);
60                                 }
61                             }
62                         }
63                     } else {
64                         self.check_bound_args(def_id, substs_ref, &args, source_info);
65                     }
66                 }
67             }
68         }
69         self.super_terminator(terminator, location);
70     }
71
72     /// Emits a lint for function references formatted with `fmt::Pointer::fmt` by macros. These
73     /// cases are handled as operands instead of call terminators to avoid any dependence on
74     /// unstable, internal formatting details like whether `fmt` is called directly or not.
75     fn visit_operand(&mut self, operand: &Operand<'tcx>, location: Location) {
76         let source_info = *self.body.source_info(location);
77         if source_info.span.from_expansion() {
78             let op_ty = operand.ty(self.body, self.tcx);
79             if let ty::FnDef(def_id, substs_ref) = *op_ty.kind() {
80                 if self.tcx.is_diagnostic_item(sym::pointer_trait_fmt, def_id) {
81                     let param_ty = substs_ref.type_at(0);
82                     if let Some((fn_id, fn_substs)) = FunctionItemRefChecker::is_fn_ref(param_ty) {
83                         // The operand's ctxt wouldn't display the lint since it's inside a macro so
84                         // we have to use the callsite's ctxt.
85                         let callsite_ctxt = source_info.span.source_callsite().ctxt();
86                         let span = source_info.span.with_ctxt(callsite_ctxt);
87                         self.emit_lint(fn_id, fn_substs, source_info, span);
88                     }
89                 }
90             }
91         }
92         self.super_operand(operand, location);
93     }
94 }
95
96 impl<'tcx> FunctionItemRefChecker<'_, 'tcx> {
97     /// Emits a lint for function reference arguments bound by `fmt::Pointer` in calls to the
98     /// function defined by `def_id` with the substitutions `substs_ref`.
99     fn check_bound_args(
100         &self,
101         def_id: DefId,
102         substs_ref: SubstsRef<'tcx>,
103         args: &[Operand<'tcx>],
104         source_info: SourceInfo,
105     ) {
106         let param_env = self.tcx.param_env(def_id);
107         let bounds = param_env.caller_bounds();
108         for bound in bounds {
109             if let Some(bound_ty) = self.is_pointer_trait(&bound.kind().skip_binder()) {
110                 // Get the argument types as they appear in the function signature.
111                 let arg_defs = self.tcx.fn_sig(def_id).skip_binder().inputs();
112                 for (arg_num, arg_def) in arg_defs.iter().enumerate() {
113                     // For all types reachable from the argument type in the fn sig
114                     for generic_inner_ty in arg_def.walk() {
115                         if let GenericArgKind::Type(inner_ty) = generic_inner_ty.unpack() {
116                             // If the inner type matches the type bound by `Pointer`
117                             if TyS::same_type(inner_ty, bound_ty) {
118                                 // Do a substitution using the parameters from the callsite
119                                 let subst_ty = inner_ty.subst(self.tcx, substs_ref);
120                                 if let Some((fn_id, fn_substs)) =
121                                     FunctionItemRefChecker::is_fn_ref(subst_ty)
122                                 {
123                                     let span = self.nth_arg_span(args, arg_num);
124                                     self.emit_lint(fn_id, fn_substs, source_info, span);
125                                 }
126                             }
127                         }
128                     }
129                 }
130             }
131         }
132     }
133
134     /// If the given predicate is the trait `fmt::Pointer`, returns the bound parameter type.
135     fn is_pointer_trait(&self, bound: &PredicateKind<'tcx>) -> Option<Ty<'tcx>> {
136         if let ty::PredicateKind::Trait(predicate) = bound {
137             if self.tcx.is_diagnostic_item(sym::Pointer, predicate.def_id()) {
138                 Some(predicate.trait_ref.self_ty())
139             } else {
140                 None
141             }
142         } else {
143             None
144         }
145     }
146
147     /// If a type is a reference or raw pointer to the anonymous type of a function definition,
148     /// returns that function's `DefId` and `SubstsRef`.
149     fn is_fn_ref(ty: Ty<'tcx>) -> Option<(DefId, SubstsRef<'tcx>)> {
150         let referent_ty = match ty.kind() {
151             ty::Ref(_, referent_ty, _) => Some(referent_ty),
152             ty::RawPtr(ty_and_mut) => Some(&ty_and_mut.ty),
153             _ => None,
154         };
155         referent_ty
156             .map(|ref_ty| {
157                 if let ty::FnDef(def_id, substs_ref) = *ref_ty.kind() {
158                     Some((def_id, substs_ref))
159                 } else {
160                     None
161                 }
162             })
163             .unwrap_or(None)
164     }
165
166     fn nth_arg_span(&self, args: &[Operand<'tcx>], n: usize) -> Span {
167         match &args[n] {
168             Operand::Copy(place) | Operand::Move(place) => {
169                 self.body.local_decls[place.local].source_info.span
170             }
171             Operand::Constant(constant) => constant.span,
172         }
173     }
174
175     fn emit_lint(
176         &self,
177         fn_id: DefId,
178         fn_substs: SubstsRef<'tcx>,
179         source_info: SourceInfo,
180         span: Span,
181     ) {
182         let lint_root = self.body.source_scopes[source_info.scope]
183             .local_data
184             .as_ref()
185             .assert_crate_local()
186             .lint_root;
187         let fn_sig = self.tcx.fn_sig(fn_id);
188         let unsafety = fn_sig.unsafety().prefix_str();
189         let abi = match fn_sig.abi() {
190             Abi::Rust => String::from(""),
191             other_abi => {
192                 let mut s = String::from("extern \"");
193                 s.push_str(other_abi.name());
194                 s.push_str("\" ");
195                 s
196             }
197         };
198         let ident = self.tcx.item_name(fn_id).to_ident_string();
199         let ty_params = fn_substs.types().map(|ty| format!("{}", ty));
200         let const_params = fn_substs.consts().map(|c| format!("{}", c));
201         let params = ty_params.chain(const_params).join(", ");
202         let num_args = fn_sig.inputs().map_bound(|inputs| inputs.len()).skip_binder();
203         let variadic = if fn_sig.c_variadic() { ", ..." } else { "" };
204         let ret = if fn_sig.output().skip_binder().is_unit() { "" } else { " -> _" };
205         self.tcx.struct_span_lint_hir(FUNCTION_ITEM_REFERENCES, lint_root, span, |lint| {
206             lint.build("taking a reference to a function item does not give a function pointer")
207                 .span_suggestion(
208                     span,
209                     &format!("cast `{}` to obtain a function pointer", ident),
210                     format!(
211                         "{} as {}{}fn({}{}){}",
212                         if params.is_empty() { ident } else { format!("{}::<{}>", ident, params) },
213                         unsafety,
214                         abi,
215                         vec!["_"; num_args].join(", "),
216                         variadic,
217                         ret,
218                     ),
219                     Applicability::Unspecified,
220                 )
221                 .emit();
222         });
223     }
224 }