Auto merge of #7877 - dswij:no-std-fp, r=camsteffen

[`swap`] lints now check if there is `no_std` or `no_core` attribute

Closes #7858

changelog: [`swap`] lints now check if there is `no_std` or `no_core` attribute
This commit is contained in:
bors 2021-11-11 05:31:11 +00:00
commit 8389df9db7
5 changed files with 87 additions and 24 deletions

View file

@ -8,6 +8,7 @@
#![feature(rustc_private)]
#![feature(stmt_expr_attributes)]
#![feature(control_flow_enum)]
#![feature(let_else)]
#![recursion_limit = "512"]
#![cfg_attr(feature = "deny-warnings", deny(warnings))]
#![allow(clippy::missing_docs_in_private_items, clippy::must_use_candidate)]

View file

@ -2,7 +2,7 @@ use clippy_utils::diagnostics::{span_lint_and_sugg, span_lint_and_then};
use clippy_utils::source::snippet_with_applicability;
use clippy_utils::sugg::Sugg;
use clippy_utils::ty::is_type_diagnostic_item;
use clippy_utils::{can_mut_borrow_both, differing_macro_contexts, eq_expr_value};
use clippy_utils::{can_mut_borrow_both, differing_macro_contexts, eq_expr_value, std_or_core};
use if_chain::if_chain;
use rustc_errors::Applicability;
use rustc_hir::{BinOpKind, Block, Expr, ExprKind, PatKind, QPath, Stmt, StmtKind};
@ -113,6 +113,8 @@ fn generate_swap_warning(cx: &LateContext<'_>, e1: &Expr<'_>, e2: &Expr<'_>, spa
let first = Sugg::hir_with_applicability(cx, e1, "..", &mut applicability);
let second = Sugg::hir_with_applicability(cx, e2, "..", &mut applicability);
let Some(sugg) = std_or_core(cx) else { return };
span_lint_and_then(
cx,
MANUAL_SWAP,
@ -122,11 +124,11 @@ fn generate_swap_warning(cx: &LateContext<'_>, e1: &Expr<'_>, e2: &Expr<'_>, spa
diag.span_suggestion(
span,
"try",
format!("std::mem::swap({}, {})", first.mut_addr(), second.mut_addr()),
format!("{}::mem::swap({}, {})", sugg, first.mut_addr(), second.mut_addr()),
applicability,
);
if !is_xor_based {
diag.note("or maybe you should use `std::mem::replace`?");
diag.note(&format!("or maybe you should use `{}::mem::replace`?", sugg));
}
},
);
@ -187,26 +189,30 @@ fn check_suspicious_swap(cx: &LateContext<'_>, block: &Block<'_>) {
};
let span = first.span.to(second.span);
let Some(sugg) = std_or_core(cx) else { return };
span_lint_and_then(cx,
ALMOST_SWAPPED,
span,
&format!("this looks like you are trying to swap{}", what),
|diag| {
if !what.is_empty() {
diag.span_suggestion(
span,
"try",
format!(
"std::mem::swap({}, {})",
lhs,
rhs,
),
Applicability::MaybeIncorrect,
);
diag.note("or maybe you should use `std::mem::replace`?");
}
});
ALMOST_SWAPPED,
span,
&format!("this looks like you are trying to swap{}", what),
|diag| {
if !what.is_empty() {
diag.span_suggestion(
span,
"try",
format!(
"{}::mem::swap({}, {})",
sugg,
lhs,
rhs,
),
Applicability::MaybeIncorrect,
);
diag.note(
&format!("or maybe you should use `{}::mem::replace`?", sugg)
);
}
});
}
}
}

View file

@ -1402,7 +1402,7 @@ pub fn recurse_or_patterns<'tcx, F: FnMut(&'tcx Pat<'tcx>)>(pat: &'tcx Pat<'tcx>
/// Checks for the `#[automatically_derived]` attribute all `#[derive]`d
/// implementations have.
pub fn is_automatically_derived(attrs: &[ast::Attribute]) -> bool {
attrs.iter().any(|attr| attr.has_name(sym::automatically_derived))
has_attr(attrs, sym::automatically_derived)
}
/// Remove blocks around an expression.
@ -1524,20 +1524,29 @@ pub fn clip(tcx: TyCtxt<'_>, u: u128, ity: rustc_ty::UintTy) -> u128 {
(u << amt) >> amt
}
pub fn any_parent_is_automatically_derived(tcx: TyCtxt<'_>, node: HirId) -> bool {
pub fn has_attr(attrs: &[ast::Attribute], symbol: Symbol) -> bool {
attrs.iter().any(|attr| attr.has_name(symbol))
}
pub fn any_parent_has_attr(tcx: TyCtxt<'_>, node: HirId, symbol: Symbol) -> bool {
let map = &tcx.hir();
let mut prev_enclosing_node = None;
let mut enclosing_node = node;
while Some(enclosing_node) != prev_enclosing_node {
if is_automatically_derived(map.attrs(enclosing_node)) {
if has_attr(map.attrs(enclosing_node), symbol) {
return true;
}
prev_enclosing_node = Some(enclosing_node);
enclosing_node = map.get_parent_item(enclosing_node);
}
false
}
pub fn any_parent_is_automatically_derived(tcx: TyCtxt<'_>, node: HirId) -> bool {
any_parent_has_attr(tcx, node, sym::automatically_derived)
}
/// Matches a function call with the given path and returns the arguments.
///
/// Usage:
@ -1800,6 +1809,16 @@ pub fn is_expr_final_block_expr(tcx: TyCtxt<'_>, expr: &Expr<'_>) -> bool {
matches!(get_parent_node(tcx, expr.hir_id), Some(Node::Block(..)))
}
pub fn std_or_core(cx: &LateContext<'_>) -> Option<&'static str> {
if !is_no_std_crate(cx) {
Some("std")
} else if !is_no_core_crate(cx) {
Some("core")
} else {
None
}
}
pub fn is_no_std_crate(cx: &LateContext<'_>) -> bool {
cx.tcx.hir().attrs(hir::CRATE_HIR_ID).iter().any(|attr| {
if let ast::AttrKind::Normal(ref attr, _) = attr.kind {
@ -1810,6 +1829,16 @@ pub fn is_no_std_crate(cx: &LateContext<'_>) -> bool {
})
}
pub fn is_no_core_crate(cx: &LateContext<'_>) -> bool {
cx.tcx.hir().attrs(hir::CRATE_HIR_ID).iter().any(|attr| {
if let ast::AttrKind::Normal(ref attr, _) = attr.kind {
attr.path == sym::no_core
} else {
false
}
})
}
/// Check if parent of a hir node is a trait implementation block.
/// For example, `f` in
/// ```rust,ignore

View file

@ -0,0 +1,15 @@
#![no_std]
#![feature(lang_items, start, libc)]
#![crate_type = "lib"]
use core::panic::PanicInfo;
#[warn(clippy::all)]
fn main() {
// TODO: do somethjing with swap
let mut a = 42;
let mut b = 1337;
a = b;
b = a;
}

View file

@ -0,0 +1,12 @@
error: this looks like you are trying to swap `a` and `b`
--> $DIR/no_std_swap.rs:13:5
|
LL | / a = b;
LL | | b = a;
| |_________^ help: try: `core::mem::swap(&mut a, &mut b)`
|
= note: `-D clippy::almost-swapped` implied by `-D warnings`
= note: or maybe you should use `core::mem::replace`?
error: aborting due to previous error