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::{
8 subst::{GenericArgKind, Subst, SubstsRef},
9 EarlyBinder, PredicateKind, Ty, TyCtxt,
11 use rustc_session::lint::builtin::FUNCTION_ITEM_REFERENCES;
12 use rustc_span::{symbol::sym, Span};
13 use rustc_target::spec::abi::Abi;
17 pub struct FunctionItemReferences;
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);
26 struct FunctionItemRefChecker<'a, 'tcx> {
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 {
46 let source_info = *self.body.source_info(location);
47 let func_ty = func.ty(self.body, self.tcx);
48 if let ty::FnDef(def_id, substs_ref) = *func_ty.kind() {
49 // Handle calls to `transmute`
50 if self.tcx.is_diagnostic_item(sym::transmute, def_id) {
51 let arg_ty = args[0].ty(self.body, self.tcx);
52 for generic_inner_ty in arg_ty.walk() {
53 if let GenericArgKind::Type(inner_ty) = generic_inner_ty.unpack() {
54 if let Some((fn_id, fn_substs)) =
55 FunctionItemRefChecker::is_fn_ref(inner_ty)
57 let span = self.nth_arg_span(&args, 0);
58 self.emit_lint(fn_id, fn_substs, source_info, span);
63 self.check_bound_args(def_id, substs_ref, &args, source_info);
67 self.super_terminator(terminator, location);
71 impl<'tcx> FunctionItemRefChecker<'_, 'tcx> {
72 /// Emits a lint for function reference arguments bound by `fmt::Pointer` in calls to the
73 /// function defined by `def_id` with the substitutions `substs_ref`.
77 substs_ref: SubstsRef<'tcx>,
78 args: &[Operand<'tcx>],
79 source_info: SourceInfo,
81 let param_env = self.tcx.param_env(def_id);
82 let bounds = param_env.caller_bounds();
84 if let Some(bound_ty) = self.is_pointer_trait(&bound.kind().skip_binder()) {
85 // Get the argument types as they appear in the function signature.
86 let arg_defs = self.tcx.fn_sig(def_id).skip_binder().inputs();
87 for (arg_num, arg_def) in arg_defs.iter().enumerate() {
88 // For all types reachable from the argument type in the fn sig
89 for generic_inner_ty in arg_def.walk() {
90 if let GenericArgKind::Type(inner_ty) = generic_inner_ty.unpack() {
91 // If the inner type matches the type bound by `Pointer`
92 if inner_ty == bound_ty {
93 // Do a substitution using the parameters from the callsite
94 let subst_ty = EarlyBinder(inner_ty).subst(self.tcx, substs_ref);
95 if let Some((fn_id, fn_substs)) =
96 FunctionItemRefChecker::is_fn_ref(subst_ty)
98 let mut span = self.nth_arg_span(args, arg_num);
99 if span.from_expansion() {
100 // The operand's ctxt wouldn't display the lint since it's inside a macro so
101 // we have to use the callsite's ctxt.
102 let callsite_ctxt = span.source_callsite().ctxt();
103 span = span.with_ctxt(callsite_ctxt);
105 self.emit_lint(fn_id, fn_substs, source_info, span);
115 /// If the given predicate is the trait `fmt::Pointer`, returns the bound parameter type.
116 fn is_pointer_trait(&self, bound: &PredicateKind<'tcx>) -> Option<Ty<'tcx>> {
117 if let ty::PredicateKind::Trait(predicate) = bound {
118 if self.tcx.is_diagnostic_item(sym::Pointer, predicate.def_id()) {
119 Some(predicate.trait_ref.self_ty())
128 /// If a type is a reference or raw pointer to the anonymous type of a function definition,
129 /// returns that function's `DefId` and `SubstsRef`.
130 fn is_fn_ref(ty: Ty<'tcx>) -> Option<(DefId, SubstsRef<'tcx>)> {
131 let referent_ty = match ty.kind() {
132 ty::Ref(_, referent_ty, _) => Some(referent_ty),
133 ty::RawPtr(ty_and_mut) => Some(&ty_and_mut.ty),
138 if let ty::FnDef(def_id, substs_ref) = *ref_ty.kind() {
139 Some((def_id, substs_ref))
147 fn nth_arg_span(&self, args: &[Operand<'tcx>], n: usize) -> Span {
149 Operand::Copy(place) | Operand::Move(place) => {
150 self.body.local_decls[place.local].source_info.span
152 Operand::Constant(constant) => constant.span,
159 fn_substs: SubstsRef<'tcx>,
160 source_info: SourceInfo,
163 let lint_root = self.body.source_scopes[source_info.scope]
166 .assert_crate_local()
168 let fn_sig = self.tcx.fn_sig(fn_id);
169 let unsafety = fn_sig.unsafety().prefix_str();
170 let abi = match fn_sig.abi() {
171 Abi::Rust => String::from(""),
173 let mut s = String::from("extern \"");
174 s.push_str(other_abi.name());
179 let ident = self.tcx.item_name(fn_id).to_ident_string();
180 let ty_params = fn_substs.types().map(|ty| format!("{}", ty));
181 let const_params = fn_substs.consts().map(|c| format!("{}", c));
182 let params = ty_params.chain(const_params).join(", ");
183 let num_args = fn_sig.inputs().map_bound(|inputs| inputs.len()).skip_binder();
184 let variadic = if fn_sig.c_variadic() { ", ..." } else { "" };
185 let ret = if fn_sig.output().skip_binder().is_unit() { "" } else { " -> _" };
186 self.tcx.struct_span_lint_hir(FUNCTION_ITEM_REFERENCES, lint_root, span, |lint| {
187 lint.build("taking a reference to a function item does not give a function pointer")
190 &format!("cast `{}` to obtain a function pointer", ident),
192 "{} as {}{}fn({}{}){}",
193 if params.is_empty() { ident } else { format!("{}::<{}>", ident, params) },
196 vec!["_"; num_args].join(", "),
200 Applicability::Unspecified,