Skip to main content

rustc_mir_transform/
function_item_references.rs

1use itertools::Itertools;
2use rustc_abi::ExternAbi;
3use rustc_hir::def_id::DefId;
4use rustc_lint_defs::builtin::FUNCTION_ITEM_REFERENCES;
5use rustc_middle::mir::*;
6use rustc_middle::ty::{self, CallerBoundsIterator, EarlyBinder, GenericArgs, Ty, TyCtxt};
7use rustc_span::{Span, Spanned, sym};
8
9use crate::diagnostics;
10
11pub(super) struct FunctionItemReferences;
12
13impl<'tcx> crate::MirLint<'tcx> for FunctionItemReferences {
14    fn run_lint(&self, tcx: TyCtxt<'tcx>, body: &Body<'tcx>) {
15        let mut checker = FunctionItemRefChecker { tcx, body };
16        for bb in body.basic_blocks.iter() {
17            checker.check_terminator(bb.terminator())
18        }
19    }
20}
21
22struct FunctionItemRefChecker<'a, 'tcx> {
23    tcx: TyCtxt<'tcx>,
24    body: &'a Body<'tcx>,
25}
26
27impl<'tcx> FunctionItemRefChecker<'_, 'tcx> {
28    /// Emits a lint for function reference arguments bound by `fmt::Pointer` or passed to
29    /// `transmute`. This only handles arguments in calls outside macro expansions to avoid double
30    /// counting function references formatted as pointers by macros.
31    fn check_terminator(&mut self, terminator: &Terminator<'tcx>) {
32        if let TerminatorKind::Call {
33            func,
34            args,
35            destination: _,
36            target: _,
37            unwind: _,
38            call_source: _,
39            fn_span: _,
40        } = &terminator.kind
41        {
42            if args.is_empty() {
43                // This lint is applied to function arguments, we have nothing to check here.
44                return;
45            }
46            let source_info = terminator.source_info;
47            let func_ty = func.ty(self.body, self.tcx);
48            if let ty::FnDef(def_id, args_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].node.ty(self.body, self.tcx);
52                    for inner_ty in arg_ty.walk().filter_map(|arg| arg.as_type()) {
53                        if let Some((fn_id, fn_args)) = FunctionItemRefChecker::is_fn_ref(inner_ty)
54                        {
55                            let span = self.nth_arg_span(args, 0);
56                            self.emit_lint(fn_id, fn_args, source_info, span);
57                        }
58                    }
59                } else {
60                    self.check_bound_args(
61                        def_id,
62                        args_ref.no_bound_vars().unwrap(),
63                        args,
64                        source_info,
65                    );
66                }
67            }
68        }
69    }
70
71    /// Emits a lint for function reference arguments bound by `fmt::Pointer` in calls to the
72    /// function defined by `def_id` with the generic parameters `args_ref`.
73    fn check_bound_args(
74        &self,
75        def_id: DefId,
76        args_ref: GenericArgs<'tcx>,
77        args: &[Spanned<Operand<'tcx>>],
78        source_info: SourceInfo,
79    ) {
80        let param_env: ty::ParamEnv<'tcx> = self.tcx.param_env(def_id);
81        let Some(pointer_trait) = self.tcx.get_diagnostic_item(sym::Pointer) else {
82            return;
83        };
84
85        for bound in param_env
86            .caller_bounds()
87            .trait_clauses(self.tcx)
88            .with_polarity(ty::ClausePolarity::Positive)
89            .for_trait(pointer_trait)
90            .iter()
91        {
92            let bound_ty = bound.self_ty().skip_binder();
93
94            // Get the argument types as they appear in the function signature.
95            let arg_defs = self.tcx.fn_sig(def_id).instantiate_identity().skip_binder().inputs();
96            for (arg_num, arg_def) in arg_defs.iter().enumerate() {
97                // For all types reachable from the argument type in the fn sig
98                for inner_ty in arg_def.walk().filter_map(|arg| arg.as_type()) {
99                    // If the inner type matches the type bound by `Pointer`
100                    if inner_ty == bound_ty {
101                        // Do an instantiation using the parameters from the callsite
102                        let instantiated_ty = EarlyBinder::bind(self.tcx, inner_ty)
103                            .instantiate(self.tcx, args_ref)
104                            .skip_norm_wip();
105                        if let Some((fn_id, fn_args)) =
106                            FunctionItemRefChecker::is_fn_ref(instantiated_ty)
107                        {
108                            let mut span = self.nth_arg_span(args, arg_num);
109                            if span.from_expansion() {
110                                // The operand's ctxt wouldn't display the lint since it's
111                                // inside a macro so we have to use the callsite's ctxt.
112                                let callsite_ctxt = span.source_callsite().ctxt();
113                                span = span.with_ctxt(callsite_ctxt);
114                            }
115                            self.emit_lint(fn_id, fn_args, source_info, span);
116                        }
117                    }
118                }
119            }
120        }
121    }
122
123    /// If a type is a reference or raw pointer to the anonymous type of a function definition,
124    /// returns that function's `DefId` and `GenericArgs`.
125    fn is_fn_ref(ty: Ty<'tcx>) -> Option<(DefId, GenericArgs<'tcx>)> {
126        let referent_ty = match ty.kind() {
127            ty::Ref(_, referent_ty, _) => Some(referent_ty),
128            ty::RawPtr(referent_ty, _) => Some(referent_ty),
129            _ => None,
130        };
131        referent_ty
132            .map(|ref_ty| {
133                if let ty::FnDef(def_id, args_ref) = *ref_ty.kind() {
134                    Some((def_id, args_ref.no_bound_vars().unwrap()))
135                } else {
136                    None
137                }
138            })
139            .unwrap_or(None)
140    }
141
142    fn nth_arg_span(&self, args: &[Spanned<Operand<'tcx>>], n: usize) -> Span {
143        args[n].node.span(&self.body.local_decls)
144    }
145
146    fn emit_lint(
147        &self,
148        fn_id: DefId,
149        fn_args: GenericArgs<'tcx>,
150        source_info: SourceInfo,
151        span: Span,
152    ) {
153        let lint_root = self.body.source_scopes[source_info.scope]
154            .local_data
155            .as_ref()
156            .unwrap_crate_local()
157            .lint_root;
158        // FIXME: use existing printing routines to print the function signature
159        let fn_sig = self.tcx.fn_sig(fn_id).instantiate(self.tcx, fn_args).skip_norm_wip();
160        let unsafety = fn_sig.safety().prefix_str();
161        let abi = match fn_sig.abi() {
162            ExternAbi::Rust => String::from(""),
163            other_abi => format!("extern {other_abi} "),
164        };
165        let ident = self.tcx.item_ident(fn_id);
166        let params = fn_args.terms().map(|term| format!("{term}")).join(", ");
167        let num_args = fn_sig.inputs().map_bound(|inputs| inputs.len()).skip_binder();
168        let variadic = if fn_sig.c_variadic() { ", ..." } else { "" };
169        let ret = if fn_sig.output().skip_binder().is_unit() { "" } else { " -> _" };
170        let sugg = format!(
171            "{} as {}{}fn({}{}){}",
172            if params.is_empty() { ident.to_string() } else { format!("{ident}::<{params}>") },
173            unsafety,
174            abi,
175            vec!["_"; num_args].join(", "),
176            variadic,
177            ret,
178        );
179
180        self.tcx.emit_node_span_lint(
181            FUNCTION_ITEM_REFERENCES,
182            lint_root,
183            span,
184            diagnostics::FnItemRef { span, sugg, ident },
185        );
186    }
187}