Skip to content

Commit dd4d4e2

Browse files
committed
added a lint against function references
this lint suggests casting function references to `*const ()`
1 parent 56d288f commit dd4d4e2

File tree

2 files changed

+33
-0
lines changed

2 files changed

+33
-0
lines changed

compiler/rustc_lint/src/builtin.rs

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2942,3 +2942,35 @@ 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+
if node.fn_decl().is_some() {
2961+
if let Some(ident) = node.ident() {
2962+
cx.struct_span_lint(FUNCTION_REFERENCES, referent.span, |lint| {
2963+
lint.build(&format!(
2964+
"cast {} with `as *const ()` to use it as a pointer",
2965+
ident.to_string()
2966+
))
2967+
.emit()
2968+
});
2969+
}
2970+
}
2971+
});
2972+
}
2973+
}
2974+
}
2975+
}
2976+
}

compiler/rustc_lint/src/lib.rs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -194,6 +194,7 @@ macro_rules! late_lint_mod_passes {
194194
UnreachablePub: UnreachablePub,
195195
ExplicitOutlivesRequirements: ExplicitOutlivesRequirements,
196196
InvalidValue: InvalidValue,
197+
FunctionReferences: FunctionReferences,
197198
]
198199
);
199200
};

0 commit comments

Comments
 (0)