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 = self.tcx.param_env(def_id);
81        for bound in param_env.caller_bounds().all_clauses(self.tcx).iter() {
82            if let Some(bound_ty) = self.is_pointer_trait(bound) {
83                // Get the argument types as they appear in the function signature.
84                let arg_defs =
85                    self.tcx.fn_sig(def_id).instantiate_identity().skip_binder().inputs();
86                for (arg_num, arg_def) in arg_defs.iter().enumerate() {
87                    // For all types reachable from the argument type in the fn sig
88                    for inner_ty in arg_def.walk().filter_map(|arg| arg.as_type()) {
89                        // If the inner type matches the type bound by `Pointer`
90                        if inner_ty == bound_ty {
91                            // Do an instantiation using the parameters from the callsite
92                            let instantiated_ty = EarlyBinder::bind(self.tcx, inner_ty)
93                                .instantiate(self.tcx, args_ref)
94                                .skip_norm_wip();
95                            if let Some((fn_id, fn_args)) =
96                                FunctionItemRefChecker::is_fn_ref(instantiated_ty)
97                            {
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
101                                    // inside a macro so we have to use the callsite's ctxt.
102                                    let callsite_ctxt = span.source_callsite().ctxt();
103                                    span = span.with_ctxt(callsite_ctxt);
104                                }
105                                self.emit_lint(fn_id, fn_args, source_info, span);
106                            }
107                        }
108                    }
109                }
110            }
111        }
112    }
113
114    /// If the given predicate is the trait `fmt::Pointer`, returns the bound parameter type.
115    fn is_pointer_trait(&self, bound: ty::Clause<'tcx>) -> Option<Ty<'tcx>> {
116        if let ty::ClauseKind::Trait(predicate) = bound.kind().skip_binder() {
117            self.tcx
118                .is_diagnostic_item(sym::Pointer, predicate.def_id())
119                .then(|| predicate.trait_ref.self_ty())
120        } else {
121            None
122        }
123    }
124
125    /// If a type is a reference or raw pointer to the anonymous type of a function definition,
126    /// returns that function's `DefId` and `GenericArgs`.
127    fn is_fn_ref(ty: Ty<'tcx>) -> Option<(DefId, GenericArgs<'tcx>)> {
128        let referent_ty = match ty.kind() {
129            ty::Ref(_, referent_ty, _) => Some(referent_ty),
130            ty::RawPtr(referent_ty, _) => Some(referent_ty),
131            _ => None,
132        };
133        referent_ty
134            .map(|ref_ty| {
135                if let ty::FnDef(def_id, args_ref) = *ref_ty.kind() {
136                    Some((def_id, args_ref.no_bound_vars().unwrap()))
137                } else {
138                    None
139                }
140            })
141            .unwrap_or(None)
142    }
143
144    fn nth_arg_span(&self, args: &[Spanned<Operand<'tcx>>], n: usize) -> Span {
145        args[n].node.span(&self.body.local_decls)
146    }
147
148    fn emit_lint(
149        &self,
150        fn_id: DefId,
151        fn_args: GenericArgs<'tcx>,
152        source_info: SourceInfo,
153        span: Span,
154    ) {
155        let lint_root = self.body.source_scopes[source_info.scope]
156            .local_data
157            .as_ref()
158            .unwrap_crate_local()
159            .lint_root;
160        // FIXME: use existing printing routines to print the function signature
161        let fn_sig = self.tcx.fn_sig(fn_id).instantiate(self.tcx, fn_args).skip_norm_wip();
162        let unsafety = fn_sig.safety().prefix_str();
163        let abi = match fn_sig.abi() {
164            ExternAbi::Rust => String::from(""),
165            other_abi => format!("extern {other_abi} "),
166        };
167        let ident = self.tcx.item_ident(fn_id);
168        let params = fn_args.terms().map(|term| format!("{term}")).join(", ");
169        let num_args = fn_sig.inputs().map_bound(|inputs| inputs.len()).skip_binder();
170        let variadic = if fn_sig.c_variadic() { ", ..." } else { "" };
171        let ret = if fn_sig.output().skip_binder().is_unit() { "" } else { " -> _" };
172        let sugg = format!(
173            "{} as {}{}fn({}{}){}",
174            if params.is_empty() { ident.to_string() } else { format!("{ident}::<{params}>") },
175            unsafety,
176            abi,
177            vec!["_"; num_args].join(", "),
178            variadic,
179            ret,
180        );
181
182        self.tcx.emit_node_span_lint(
183            FUNCTION_ITEM_REFERENCES,
184            lint_root,
185            span,
186            diagnostics::FnItemRef { span, sugg, ident },
187        );
188    }
189}