Do not suppress temporary_cstring_as_ptr in macros.

This commit is contained in:
Camille GILLOT 2023-04-04 18:31:25 +00:00
parent be8e5ba157
commit 8528ac6e35
3 changed files with 33 additions and 43 deletions

View file

@ -2,9 +2,9 @@ use crate::lints::CStringPtr;
use crate::LateContext;
use crate::LateLintPass;
use crate::LintContext;
use rustc_hir::{Expr, ExprKind, PathSegment};
use rustc_hir::{Expr, ExprKind};
use rustc_middle::ty;
use rustc_span::{symbol::sym, ExpnKind, Span};
use rustc_span::{symbol::sym, Span};
declare_lint! {
/// The `temporary_cstring_as_ptr` lint detects getting the inner pointer of
@ -34,47 +34,14 @@ declare_lint! {
declare_lint_pass!(TemporaryCStringAsPtr => [TEMPORARY_CSTRING_AS_PTR]);
fn in_macro(span: Span) -> bool {
if span.from_expansion() {
!matches!(span.ctxt().outer_expn_data().kind, ExpnKind::Desugaring(..))
} else {
false
}
}
fn first_method_call<'tcx>(
expr: &'tcx Expr<'tcx>,
) -> Option<(&'tcx PathSegment<'tcx>, &'tcx Expr<'tcx>)> {
if let ExprKind::MethodCall(path, receiver, args, ..) = &expr.kind {
if args.iter().any(|e| e.span.from_expansion()) || receiver.span.from_expansion() {
None
} else {
Some((path, *receiver))
}
} else {
None
}
}
impl<'tcx> LateLintPass<'tcx> for TemporaryCStringAsPtr {
fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) {
if in_macro(expr.span) {
return;
}
match first_method_call(expr) {
Some((path, unwrap_arg)) if path.ident.name == sym::as_ptr => {
let as_ptr_span = path.ident.span;
match first_method_call(unwrap_arg) {
Some((path, receiver))
if path.ident.name == sym::unwrap || path.ident.name == sym::expect =>
{
lint_cstring_as_ptr(cx, as_ptr_span, receiver, unwrap_arg);
}
_ => return,
}
}
_ => return,
if let ExprKind::MethodCall(as_ptr_path, as_ptr_receiver, ..) = expr.kind
&& as_ptr_path.ident.name == sym::as_ptr
&& let ExprKind::MethodCall(unwrap_path, unwrap_receiver, ..) = as_ptr_receiver.kind
&& (unwrap_path.ident.name == sym::unwrap || unwrap_path.ident.name == sym::expect)
{
lint_cstring_as_ptr(cx, as_ptr_path.ident.span, unwrap_receiver, as_ptr_receiver);
}
}
}