Skip to content

Commit 3214de7

Browse files
committed
modified lint to work with MIR
Working with MIR let's us exclude expressions like `&fn_name as &dyn Something` and `(&fn_name)()`. Also added ABI, unsafety and whether a function is variadic in the lint suggestion, included the `&` in the span of the lint and updated the test.
1 parent 975547d commit 3214de7

File tree

7 files changed

+322
-59
lines changed

7 files changed

+322
-59
lines changed

compiler/rustc_lint/src/builtin.rs

-34
Original file line numberDiff line numberDiff line change
@@ -2942,37 +2942,3 @@ impl<'tcx> LateLintPass<'tcx> for ClashingExternDeclarations {
29422942
}
29432943
}
29442944
}
2945-
2946-
declare_lint! {
2947-
FUNCTION_REFERENCES,
2948-
Warn,
2949-
"suggest casting functions to pointers when attempting to take references"
2950-
}
2951-
2952-
declare_lint_pass!(FunctionReferences => [FUNCTION_REFERENCES]);
2953-
2954-
impl<'tcx> LateLintPass<'tcx> for FunctionReferences {
2955-
fn check_expr(&mut self, cx: &LateContext<'_>, e: &hir::Expr<'_>) {
2956-
if let hir::ExprKind::AddrOf(hir::BorrowKind::Ref, _, referent) = e.kind {
2957-
if let hir::ExprKind::Path(qpath) = &referent.kind {
2958-
if let Some(def_id) = cx.qpath_res(qpath, referent.hir_id).opt_def_id() {
2959-
cx.tcx.hir().get_if_local(def_id).map(|node| {
2960-
node.fn_decl().map(|decl| {
2961-
if let Some(ident) = node.ident() {
2962-
cx.struct_span_lint(FUNCTION_REFERENCES, referent.span, |lint| {
2963-
let num_args = decl.inputs.len();
2964-
lint.build(&format!(
2965-
"cast `{}` with `as *const fn({}) -> _` to use it as a pointer",
2966-
ident.to_string(),
2967-
vec!["_"; num_args].join(", ")
2968-
))
2969-
.emit()
2970-
});
2971-
}
2972-
});
2973-
});
2974-
}
2975-
}
2976-
}
2977-
}
2978-
}

compiler/rustc_lint/src/lib.rs

-1
Original file line numberDiff line numberDiff line change
@@ -194,7 +194,6 @@ macro_rules! late_lint_mod_passes {
194194
UnreachablePub: UnreachablePub,
195195
ExplicitOutlivesRequirements: ExplicitOutlivesRequirements,
196196
InvalidValue: InvalidValue,
197-
FunctionReferences: FunctionReferences,
198197
]
199198
);
200199
};
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,158 @@
1+
use rustc_hir::def_id::DefId;
2+
use rustc_middle::mir::visit::Visitor;
3+
use rustc_middle::mir::*;
4+
use rustc_middle::ty::{self, Ty, TyCtxt};
5+
use rustc_session::lint::builtin::FUNCTION_REFERENCES;
6+
use rustc_span::Span;
7+
use rustc_target::spec::abi::Abi;
8+
9+
use crate::transform::{MirPass, MirSource};
10+
11+
pub struct FunctionReferences;
12+
13+
impl<'tcx> MirPass<'tcx> for FunctionReferences {
14+
fn run_pass(&self, tcx: TyCtxt<'tcx>, _src: MirSource<'tcx>, body: &mut Body<'tcx>) {
15+
let source_info = SourceInfo::outermost(body.span);
16+
let mut checker = FunctionRefChecker {
17+
tcx,
18+
body,
19+
potential_lints: Vec::new(),
20+
casts: Vec::new(),
21+
calls: Vec::new(),
22+
source_info,
23+
};
24+
checker.visit_body(&body);
25+
}
26+
}
27+
28+
struct FunctionRefChecker<'a, 'tcx> {
29+
tcx: TyCtxt<'tcx>,
30+
body: &'a Body<'tcx>,
31+
potential_lints: Vec<FunctionRefLint>,
32+
casts: Vec<Span>,
33+
calls: Vec<Span>,
34+
source_info: SourceInfo,
35+
}
36+
37+
impl<'a, 'tcx> Visitor<'tcx> for FunctionRefChecker<'a, 'tcx> {
38+
fn visit_basic_block_data(&mut self, block: BasicBlock, data: &BasicBlockData<'tcx>) {
39+
self.super_basic_block_data(block, data);
40+
for cast_span in self.casts.drain(..) {
41+
self.potential_lints.retain(|lint| lint.source_info.span != cast_span);
42+
}
43+
for call_span in self.calls.drain(..) {
44+
self.potential_lints.retain(|lint| lint.source_info.span != call_span);
45+
}
46+
for lint in self.potential_lints.drain(..) {
47+
lint.emit(self.tcx, self.body);
48+
}
49+
}
50+
fn visit_statement(&mut self, statement: &Statement<'tcx>, location: Location) {
51+
self.source_info = statement.source_info;
52+
self.super_statement(statement, location);
53+
}
54+
fn visit_terminator(&mut self, terminator: &Terminator<'tcx>, location: Location) {
55+
self.source_info = terminator.source_info;
56+
if let TerminatorKind::Call {
57+
func,
58+
args: _,
59+
destination: _,
60+
cleanup: _,
61+
from_hir_call: _,
62+
fn_span: _,
63+
} = &terminator.kind
64+
{
65+
let span = match func {
66+
Operand::Copy(place) | Operand::Move(place) => {
67+
self.body.local_decls[place.local].source_info.span
68+
}
69+
Operand::Constant(constant) => constant.span,
70+
};
71+
self.calls.push(span);
72+
};
73+
self.super_terminator(terminator, location);
74+
}
75+
fn visit_rvalue(&mut self, rvalue: &Rvalue<'tcx>, location: Location) {
76+
match rvalue {
77+
Rvalue::Ref(_, _, place) | Rvalue::AddressOf(_, place) => {
78+
let decl = &self.body.local_decls[place.local];
79+
if let ty::FnDef(def_id, _) = decl.ty.kind {
80+
let ident = self
81+
.body
82+
.var_debug_info
83+
.iter()
84+
.find(|info| info.source_info.span == decl.source_info.span)
85+
.map(|info| info.name.to_ident_string())
86+
.unwrap_or(self.tcx.def_path_str(def_id));
87+
let lint = FunctionRefLint { ident, def_id, source_info: self.source_info };
88+
self.potential_lints.push(lint);
89+
}
90+
}
91+
Rvalue::Cast(_, op, _) => {
92+
let op_ty = op.ty(self.body, self.tcx);
93+
if self.is_fn_ref(op_ty) {
94+
self.casts.push(self.source_info.span);
95+
}
96+
}
97+
_ => {}
98+
}
99+
self.super_rvalue(rvalue, location);
100+
}
101+
}
102+
103+
impl<'a, 'tcx> FunctionRefChecker<'a, 'tcx> {
104+
fn is_fn_ref(&self, ty: Ty<'tcx>) -> bool {
105+
let referent_ty = match ty.kind {
106+
ty::Ref(_, referent_ty, _) => Some(referent_ty),
107+
ty::RawPtr(ty_and_mut) => Some(ty_and_mut.ty),
108+
_ => None,
109+
};
110+
referent_ty
111+
.map(|ref_ty| if let ty::FnDef(..) = ref_ty.kind { true } else { false })
112+
.unwrap_or(false)
113+
}
114+
}
115+
116+
struct FunctionRefLint {
117+
ident: String,
118+
def_id: DefId,
119+
source_info: SourceInfo,
120+
}
121+
122+
impl<'tcx> FunctionRefLint {
123+
fn emit(&self, tcx: TyCtxt<'tcx>, body: &Body<'tcx>) {
124+
let def_id = self.def_id;
125+
let source_info = self.source_info;
126+
let lint_root = body.source_scopes[source_info.scope]
127+
.local_data
128+
.as_ref()
129+
.assert_crate_local()
130+
.lint_root;
131+
let fn_sig = tcx.fn_sig(def_id);
132+
let unsafety = fn_sig.unsafety().prefix_str();
133+
let abi = match fn_sig.abi() {
134+
Abi::Rust => String::from(""),
135+
other_abi => {
136+
let mut s = String::from("extern \"");
137+
s.push_str(other_abi.name());
138+
s.push_str("\" ");
139+
s
140+
}
141+
};
142+
let num_args = fn_sig.inputs().map_bound(|inputs| inputs.len()).skip_binder();
143+
let variadic = if fn_sig.c_variadic() { ", ..." } else { "" };
144+
let ret = if fn_sig.output().skip_binder().is_unit() { "" } else { " -> _" };
145+
tcx.struct_span_lint_hir(FUNCTION_REFERENCES, lint_root, source_info.span, |lint| {
146+
lint.build(&format!(
147+
"cast `{}` with `as {}{}fn({}{}){}` to use it as a pointer",
148+
self.ident,
149+
unsafety,
150+
abi,
151+
vec!["_"; num_args].join(", "),
152+
variadic,
153+
ret,
154+
))
155+
.emit()
156+
});
157+
}
158+
}

compiler/rustc_mir/src/transform/mod.rs

+2
Original file line numberDiff line numberDiff line change
@@ -27,6 +27,7 @@ pub mod dest_prop;
2727
pub mod dump_mir;
2828
pub mod early_otherwise_branch;
2929
pub mod elaborate_drops;
30+
pub mod function_references;
3031
pub mod generator;
3132
pub mod inline;
3233
pub mod instcombine;
@@ -266,6 +267,7 @@ fn mir_const<'tcx>(
266267
// MIR-level lints.
267268
&check_packed_ref::CheckPackedRef,
268269
&check_const_item_mutation::CheckConstItemMutation,
270+
&function_references::FunctionReferences,
269271
// What we need to do constant evaluation.
270272
&simplify::SimplifyCfg::new("initial"),
271273
&rustc_peek::SanityCheck,

compiler/rustc_session/src/lint/builtin.rs

+6
Original file line numberDiff line numberDiff line change
@@ -2645,6 +2645,11 @@ declare_lint! {
26452645
reference: "issue #76200 <https://github.com/rust-lang/rust/issues/76200>",
26462646
edition: None,
26472647
};
2648+
2649+
declare_lint! {
2650+
pub FUNCTION_REFERENCES,
2651+
Warn,
2652+
"suggest casting functions to pointers when attempting to take references",
26482653
}
26492654

26502655
declare_lint! {
@@ -2762,6 +2767,7 @@ declare_lint_pass! {
27622767
CONST_EVALUATABLE_UNCHECKED,
27632768
INEFFECTIVE_UNSTABLE_TRAIT_IMPL,
27642769
UNINHABITED_STATIC,
2770+
FUNCTION_REFERENCES,
27652771
]
27662772
}
27672773

+62-13
Original file line numberDiff line numberDiff line change
@@ -1,22 +1,71 @@
11
// check-pass
2-
fn foo() -> usize { 42 }
3-
fn bar(x: usize) -> usize { x }
4-
fn baz(x: usize, y: usize) -> usize { x + y }
2+
#![feature(c_variadic)]
3+
#![allow(dead_code)]
4+
5+
fn foo() -> u32 { 42 }
6+
fn bar(x: u32) -> u32 { x }
7+
fn baz(x: u32, y: u32) -> u32 { x + y }
8+
unsafe fn unsafe_fn() { }
9+
extern "C" fn c_fn() { }
10+
unsafe extern "C" fn unsafe_c_fn() { }
11+
unsafe extern fn variadic_fn(_x: u32, _args: ...) { }
12+
fn call_fn(f: &dyn Fn(u32) -> u32, x: u32) { f(x); }
13+
fn parameterized_call_fn<F: Fn(u32) -> u32>(f: &F, x: u32) { f(x); }
514

615
fn main() {
16+
let _zst_ref = &foo;
17+
//~^ WARN cast `foo` with `as fn() -> _` to use it as a pointer
18+
let fn_item = foo;
19+
let _indirect_ref = &fn_item;
20+
//~^ WARN cast `fn_item` with `as fn() -> _` to use it as a pointer
21+
let _cast_zst_ptr = &foo as *const _;
22+
//~^ WARN cast `foo` with `as fn() -> _` to use it as a pointer
23+
let _coerced_zst_ptr: *const _ = &foo;
24+
//~^ WARN cast `foo` with `as fn() -> _` to use it as a pointer
25+
26+
let _zst_ref = &mut foo;
27+
//~^ WARN cast `foo` with `as fn() -> _` to use it as a pointer
28+
let mut mut_fn_item = foo;
29+
let _indirect_ref = &mut mut_fn_item;
30+
//~^ WARN cast `fn_item` with `as fn() -> _` to use it as a pointer
31+
let _cast_zst_ptr = &mut foo as *mut _;
32+
//~^ WARN cast `foo` with `as fn() -> _` to use it as a pointer
33+
let _coerced_zst_ptr: *mut _ = &mut foo;
34+
//~^ WARN cast `foo` with `as fn() -> _` to use it as a pointer
35+
36+
let _cast_zst_ref = &foo as &dyn Fn() -> u32;
37+
let _coerced_zst_ref: &dyn Fn() -> u32 = &foo;
38+
39+
let _cast_zst_ref = &mut foo as &mut dyn Fn() -> u32;
40+
let _coerced_zst_ref: &mut dyn Fn() -> u32 = &mut foo;
41+
let _fn_ptr = foo as fn() -> u32;
42+
743
println!("{:p}", &foo);
8-
//~^ WARN cast `foo` with `as *const fn() -> _` to use it as a pointer
44+
//~^ WARN cast `foo` with as fn() -> _` to use it as a pointer
945
println!("{:p}", &bar);
10-
//~^ WARN cast `bar` with `as *const fn(_) -> _` to use it as a pointer
46+
//~^ WARN cast `bar` with as fn(_) -> _` to use it as a pointer
1147
println!("{:p}", &baz);
12-
//~^ WARN cast `baz` with `as *const fn(_, _) -> _` to use it as a pointer
48+
//~^ WARN cast `baz` with as fn(_, _) -> _` to use it as a pointer
49+
println!("{:p}", &unsafe_fn);
50+
//~^ WARN cast `baz` with as unsafe fn()` to use it as a pointer
51+
println!("{:p}", &c_fn);
52+
//~^ WARN cast `baz` with as extern "C" fn()` to use it as a pointer
53+
println!("{:p}", &unsafe_c_fn);
54+
//~^ WARN cast `baz` with as unsafe extern "C" fn()` to use it as a pointer
55+
println!("{:p}", &variadic_fn);
56+
//~^ WARN cast `baz` with as unsafe extern "C" fn(_, ...) -> _` to use it as a pointer
57+
println!("{:p}", &std::env::var::<String>);
58+
//~^ WARN cast `std::env::var` with as fn(_) -> _` to use it as a pointer
59+
60+
println!("{:p}", foo as fn() -> u32);
1361

14-
//should not produce any warnings
15-
println!("{:p}", foo as *const fn() -> usize);
16-
println!("{:p}", bar as *const fn(usize) -> usize);
17-
println!("{:p}", baz as *const fn(usize, usize) -> usize);
62+
unsafe {
63+
std::mem::transmute::<_, usize>(&foo);
64+
//~^ WARN cast `foo` with as fn() -> _` to use it as a pointer
65+
std::mem::transmute::<_, usize>(foo as fn() -> u32);
66+
}
1867

19-
//should not produce any warnings
20-
let fn_thing = foo;
21-
println!("{:p}", &fn_thing);
68+
(&bar)(1);
69+
call_fn(&bar, 1);
70+
parameterized_call_fn(&bar, 1);
2271
}

0 commit comments

Comments
 (0)