Skip to content

Commit

Permalink
added a lint against function references
Browse files Browse the repository at this point in the history
this lint suggests casting function references to `*const ()`
  • Loading branch information
ayrtonm committed Oct 27, 2020
1 parent 56d288f commit dd4d4e2
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 0 deletions.
32 changes: 32 additions & 0 deletions compiler/rustc_lint/src/builtin.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2942,3 +2942,35 @@ impl<'tcx> LateLintPass<'tcx> for ClashingExternDeclarations {
}
}
}

declare_lint! {
FUNCTION_REFERENCES,
Warn,
"suggest casting functions to pointers when attempting to take references"
}

declare_lint_pass!(FunctionReferences => [FUNCTION_REFERENCES]);

impl<'tcx> LateLintPass<'tcx> for FunctionReferences {
fn check_expr(&mut self, cx: &LateContext<'_>, e: &hir::Expr<'_>) {
if let hir::ExprKind::AddrOf(hir::BorrowKind::Ref, _, referent) = e.kind {
if let hir::ExprKind::Path(qpath) = &referent.kind {
if let Some(def_id) = cx.qpath_res(qpath, referent.hir_id).opt_def_id() {
cx.tcx.hir().get_if_local(def_id).map(|node| {
if node.fn_decl().is_some() {
if let Some(ident) = node.ident() {
cx.struct_span_lint(FUNCTION_REFERENCES, referent.span, |lint| {
lint.build(&format!(
"cast {} with `as *const ()` to use it as a pointer",
ident.to_string()
))
.emit()
});
}
}
});
}
}
}
}
}
1 change: 1 addition & 0 deletions compiler/rustc_lint/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -194,6 +194,7 @@ macro_rules! late_lint_mod_passes {
UnreachablePub: UnreachablePub,
ExplicitOutlivesRequirements: ExplicitOutlivesRequirements,
InvalidValue: InvalidValue,
FunctionReferences: FunctionReferences,
]
);
};
Expand Down

0 comments on commit dd4d4e2

Please sign in to comment.