diff --git a/CHANGELOG.md b/CHANGELOG.md index 437f08dd777a..3029235af577 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5163,6 +5163,7 @@ Released 2018-09-13 [`ptr_cast_constness`]: https://rust-lang.github.io/rust-clippy/master/index.html#ptr_cast_constness [`ptr_eq`]: https://rust-lang.github.io/rust-clippy/master/index.html#ptr_eq [`ptr_offset_with_cast`]: https://rust-lang.github.io/rust-clippy/master/index.html#ptr_offset_with_cast +[`ptr_to_temporary`]: https://rust-lang.github.io/rust-clippy/master/index.html#ptr_to_temporary [`pub_enum_variant_names`]: https://rust-lang.github.io/rust-clippy/master/index.html#pub_enum_variant_names [`pub_use`]: https://rust-lang.github.io/rust-clippy/master/index.html#pub_use [`pub_with_shorthand`]: https://rust-lang.github.io/rust-clippy/master/index.html#pub_with_shorthand diff --git a/clippy_lints/src/declared_lints.rs b/clippy_lints/src/declared_lints.rs index a0d181be3b18..2a1956a385f7 100644 --- a/clippy_lints/src/declared_lints.rs +++ b/clippy_lints/src/declared_lints.rs @@ -544,6 +544,7 @@ pub(crate) static LINTS: &[&crate::LintInfo] = &[ crate::ptr::MUT_FROM_REF_INFO, crate::ptr::PTR_ARG_INFO, crate::ptr_offset_with_cast::PTR_OFFSET_WITH_CAST_INFO, + crate::ptr_to_temporary::PTR_TO_TEMPORARY_INFO, crate::pub_use::PUB_USE_INFO, crate::question_mark::QUESTION_MARK_INFO, crate::question_mark_used::QUESTION_MARK_USED_INFO, diff --git a/clippy_lints/src/lib.rs b/clippy_lints/src/lib.rs index 1609eb396b43..11d95849cf62 100644 --- a/clippy_lints/src/lib.rs +++ b/clippy_lints/src/lib.rs @@ -1,6 +1,7 @@ #![feature(array_windows)] #![feature(binary_heap_into_iter_sorted)] #![feature(box_patterns)] +#![feature(exclusive_range_pattern)] #![feature(if_let_guard)] #![feature(iter_intersperse)] #![feature(let_chains)] @@ -262,6 +263,7 @@ mod permissions_set_readonly_false; mod precedence; mod ptr; mod ptr_offset_with_cast; +mod ptr_to_temporary; mod pub_use; mod question_mark; mod question_mark_used; @@ -1082,6 +1084,7 @@ pub fn register_plugins(store: &mut rustc_lint::LintStore, sess: &Session, conf: store.register_late_pass(|_| Box::new(manual_float_methods::ManualFloatMethods)); store.register_late_pass(|_| Box::new(four_forward_slashes::FourForwardSlashes)); store.register_late_pass(|_| Box::new(error_impl_error::ErrorImplError)); + store.register_late_pass(move |_| Box::new(ptr_to_temporary::PtrToTemporary)); // add lints here, do not remove this comment, it's used in `new_lint` } diff --git a/clippy_lints/src/ptr_to_temporary.rs b/clippy_lints/src/ptr_to_temporary.rs new file mode 100644 index 000000000000..52cf1724f2b9 --- /dev/null +++ b/clippy_lints/src/ptr_to_temporary.rs @@ -0,0 +1,355 @@ +use clippy_utils::consts::is_promotable; +use clippy_utils::diagnostics::{span_lint_and_note, span_lint_hir_and_then}; +use clippy_utils::mir::{location_to_node, StatementOrTerminator}; +use rustc_data_structures::fx::FxHashMap; +use rustc_hir::def_id::{DefId, LocalDefId}; +use rustc_hir::intravisit::FnKind; +use rustc_hir::{Body, BorrowKind, Expr, ExprKind, FnDecl, HirId, ItemKind, OwnerNode}; +use rustc_lint::{LateContext, LateLintPass}; +use rustc_middle::mir::visit::{MutatingUseContext, PlaceContext, Visitor}; +use rustc_middle::mir::{ + self, BasicBlock, BasicBlockData, CallSource, Local, Location, Place, PlaceRef, ProjectionElem, Rvalue, SourceInfo, + StatementKind, TerminatorKind, +}; +use rustc_session::{declare_lint_pass, declare_tool_lint}; +use rustc_span::{sym, Span, Symbol}; + +declare_clippy_lint! { + /// ### What it does + /// Checks for raw pointers pointing to temporary values that will **not** be promoted to a + /// constant through + /// [constant promotion](https://doc.rust-lang.org/stable/reference/destructors.html#constant-promotion). + /// + /// ### Why is this bad? + /// Usage of such a pointer will result in Undefined Behavior, as the pointer will stop + /// pointing to valid stack memory once the temporary is dropped. + /// + /// ### Known problems + /// Expects any call to methods named `as_ptr` or `as_mut_ptr` returning a raw pointer to have + /// that raw pointer point to data owned by self. Essentially, it will lint all temporary + /// `as_ptr` calls even if the pointer doesn't point to the temporary. + /// + /// ### Example + /// ```rust,ignore + /// fn returning_temp() -> *const i32 { + /// let x = 0; + /// &x as *const i32 + /// } + /// + /// let px = returning_temp(); + /// unsafe { *px }; // ⚠️ + /// let pv = vec![].as_ptr(); + /// unsafe { *pv }; // ⚠️ + /// ``` + #[clippy::version = "1.72.0"] + pub PTR_TO_TEMPORARY, + // TODO: Let's make it warn-by-default for now, and change this to deny-by-default once we know + // there are no major FPs + suspicious, + "disallows obtaining raw pointers to temporary values" +} +declare_lint_pass!(PtrToTemporary => [PTR_TO_TEMPORARY]); + +impl<'tcx> LateLintPass<'tcx> for PtrToTemporary { + fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx Expr<'tcx>) { + check_for_returning_raw_ptr(cx, expr); + } + + fn check_fn( + &mut self, + cx: &LateContext<'tcx>, + _: FnKind<'_>, + _: &FnDecl<'_>, + _: &Body<'_>, + _: Span, + def_id: LocalDefId, + ) { + let mir = cx.tcx.optimized_mir(def_id); + + // Collect all local assignments in this body. This is faster than continuously passing over the + // body every time we want to get the assignments. + let mut assignments = LocalAssignmentsVisitor { + results: FxHashMap::default(), + }; + assignments.visit_body(mir); + + let mut v = DanglingPtrVisitor { + cx, + body: mir, + results: vec![], + local_assignments: assignments.results, + }; + v.visit_body(mir); + + for (span, hir_id, ident) in v.results { + // TODO: We need to lint on the call in question instead, so lint attributes work fine. I'm not sure + // how to though + span_lint_hir_and_then( + cx, + PTR_TO_TEMPORARY, + hir_id, + span, + &format!("calling `{ident}` on a temporary value"), + |diag| { + diag.note( + "usage of this pointer will cause Undefined Behavior as the temporary will be deallocated at \ + the end of the statement, yet the pointer will continue pointing to it, resulting in a \ + dangling pointer", + ); + }, + ); + } + } +} + +/// Check for returning raw pointers to temporaries that are not promoted to a constant +fn check_for_returning_raw_ptr<'tcx>(cx: &LateContext<'tcx>, expr: &'tcx Expr<'tcx>) -> bool { + // Get the final return statement if this is a return statement, or don't lint + let expr = if let ExprKind::Ret(Some(expr)) = expr.kind { + expr + } else if let OwnerNode::Item(parent) = cx.tcx.hir().owner(cx.tcx.hir().get_parent_item(expr.hir_id)) + && let ItemKind::Fn(_, _, body) = parent.kind + && let block = cx.tcx.hir().body(body).value + && let ExprKind::Block(block, _) = block.kind + && let Some(final_block_expr) = block.expr + && final_block_expr.hir_id == expr.hir_id + { + expr + } else { + return false; + }; + + if let ExprKind::Cast(cast_expr, _) = expr.kind + && let ExprKind::AddrOf(BorrowKind::Ref, _, e) = cast_expr.kind + && !is_promotable(cx, e) + { + span_lint_and_note( + cx, + PTR_TO_TEMPORARY, + expr.span, + "returning a raw pointer to a temporary value that cannot be promoted to a constant", + None, + "usage of this pointer by callers will cause Undefined Behavior as the temporary will be deallocated at \ + the end of the statement, yet the pointer will continue pointing to it, resulting in a dangling pointer", + ); + + return true; + } + + false +} + +struct LocalAssignmentsVisitor { + results: FxHashMap>, +} + +impl Visitor<'_> for LocalAssignmentsVisitor { + fn visit_place(&mut self, place: &Place<'_>, ctxt: PlaceContext, loc: Location) { + if matches!( + ctxt, + PlaceContext::MutatingUse( + MutatingUseContext::Store | MutatingUseContext::Call | MutatingUseContext::Borrow + ) + ) { + self.results.entry(place.local).or_insert(vec![]).push(loc); + } + } +} + +struct DanglingPtrVisitor<'a, 'tcx> { + cx: &'a LateContext<'tcx>, + body: &'tcx mir::Body<'tcx>, + local_assignments: FxHashMap>, + results: Vec<(Span, HirId, Symbol)>, +} + +impl<'tcx> Visitor<'tcx> for DanglingPtrVisitor<'_, 'tcx> { + fn visit_basic_block_data(&mut self, _: BasicBlock, data: &BasicBlockData<'tcx>) { + let Self { + cx, + body, + local_assignments, + results, + } = self; + + if let Some(term) = &data.terminator + && let TerminatorKind::Call { + func, + args, + destination, + target: Some(target), + call_source: CallSource::Normal, + .. + } = &term.kind + && destination.ty(&body.local_decls, cx.tcx).ty.is_unsafe_ptr() + && let [recv] = args.as_slice() + && let Some(recv) = recv.place() + && let Some((def_id, _)) = func.const_fn_def() + && let Some(ident) = returns_ptr_to_self(cx, def_id) + && let Ok(recv) = traverse_up_until_owned(body, local_assignments, recv) + { + + check_for_dangling( + body, + *target, + recv, + destination.as_ref(), + term.source_info, + ident, + results, + ); + } + } +} + +fn check_for_dangling<'tcx>( + body: &mir::Body<'tcx>, + bb: BasicBlock, + mut recv: PlaceRef<'tcx>, + ptr: PlaceRef<'_>, + source_info: SourceInfo, + ident: Symbol, + results: &mut Vec<(Span, HirId, Symbol)>, +) { + let data = &body.basic_blocks[bb]; + let mut recv_dead = false; + + // If there's a `Drop`, we must include the statements in its target so we don't miss any + // potentially important `StorageDead`s. + let rest = vec![]; + let rest = if let Some(term) = &data.terminator && let TerminatorKind::Drop { place, target, .. } = term.kind { + // This indicates a bug in our heuristic. It's normally fine if the `Drop` is present, but + // if it isn't (i.e., no drop glue) then we may have FNs, or worse. Let's catch this early + // if there are upstream MIR changes. + debug_assert_eq!(place.as_ref(), recv, "dropped place is not receiver"); + // In release mode, let's prevent a few FPs where `Drop` is present. + recv = place.as_ref(); + + &body.basic_blocks[target].statements + } else { + &rest + }; + + for dead_local in data.statements.iter().chain(rest).filter_map(|stmt| { + if let StatementKind::StorageDead(local) = stmt.kind { + return Some(local); + } + + None + }) { + match (dead_local == recv.local, dead_local == ptr.local) { + (true, false) => recv_dead = true, + (false, true) if recv_dead => { + results.push(( + source_info.span, + body.source_scopes[source_info.scope] + .local_data + .clone() + .assert_crate_local() + .lint_root, + ident, + )); + }, + _ => continue, + } + } +} + +/// Traverses the MIR backwards until it finds owned data. This can be assumed to be the dropped +/// data in the next `Drop` terminator, if not this indicates a bug in our heuristic. +fn traverse_up_until_owned<'tcx>( + body: &'tcx mir::Body<'tcx>, + local_assignments: &FxHashMap>, + start: Place<'tcx>, +) -> Result, TraverseError> { + traverse_up_until_owned_inner(body, local_assignments, start.as_ref(), 0) +} + +fn traverse_up_until_owned_inner<'tcx>( + body: &'tcx mir::Body<'tcx>, + local_assignments: &FxHashMap>, + current_place: PlaceRef<'tcx>, + depth: usize, +) -> Result, TraverseError> { + if depth > 100 { + return Err(TraverseError::MaxDepthReached); + } + let Some(current) = local_assignments.get(¤t_place.local) else { + return Err(TraverseError::NoAssignments); + }; + if current.is_empty() { + return Err(TraverseError::NoAssignments); + } + let [current] = current.as_slice() else { + return Err(TraverseError::TooManyAssignments); + }; + let current = location_to_node(body, *current); + let next = match current { + StatementOrTerminator::Statement(stmt) if let StatementKind::Assign(box (_, rvalue)) = &stmt.kind => { + match rvalue { + Rvalue::Use(op) | Rvalue::Cast(_, op, _) => { + let Some(place) = op.place() else { + return Err(TraverseError::LikelyPromoted); + }; + // If there's a field access, this is likely to be accessing `.0` on a + // `Unique`. We need a better heuristic for this though, as this may lead to + // some FPs. + if let Some(place) = place.iter_projections().find_map(|proj| { + if matches!(proj.1, ProjectionElem::Field(_, _)) { + return Some(proj.0); + } + None + }) { + return Ok(place); + } + place.as_ref() + } + Rvalue::Ref(_, _, place) => { + if !place.has_deref() { + return Ok(place.as_ref()); + } + place.as_ref() + } + // Give up if we can't determine it's dangling with near 100% accuracy + _ => return Err(TraverseError::InvalidOp), + } + } + StatementOrTerminator::Terminator(term) if let TerminatorKind::Call { args, .. } = &term.kind + && let [arg] = args.as_slice() => + { + let Some(place) = arg.place() else { + return Err(TraverseError::LikelyPromoted); + }; + place.as_ref() + } + // Give up if we can't determine it's dangling with near 100% accuracy + _ => return Err(TraverseError::InvalidOp), + }; + + traverse_up_until_owned_inner(body, local_assignments, next, depth + 1) +} + +enum TraverseError { + NoAssignments, + TooManyAssignments, + MaxDepthReached, + LikelyPromoted, + InvalidOp, +} + +/// Whether the call returns a raw pointer to data owned by self, i.e., `as_ptr` and friends. If so, +/// if it's temporary it will be dangling and we should lint it. Returns the name of the call if so. +fn returns_ptr_to_self(cx: &LateContext<'_>, def_id: DefId) ->Option { + let path = cx.tcx.def_path(def_id).data; + + if let [.., last] = &*path + && let Some(ident) = last.data.get_opt_name() + && (ident == sym::as_ptr || ident == sym!(as_mut_ptr)) + { + return Some(ident); + } + + // TODO: More checks here. We want to lint most libstd functions that return a pointer that + // aren't named `as_ptr`. + None +} diff --git a/clippy_utils/src/consts.rs b/clippy_utils/src/consts.rs index 419b139f4002..b2d5d0403f3a 100644 --- a/clippy_utils/src/consts.rs +++ b/clippy_utils/src/consts.rs @@ -1,7 +1,8 @@ #![allow(clippy::float_cmp)] use crate::source::{get_source_text, walk_span_to_context}; -use crate::{clip, is_direct_expn_of, sext, unsext}; +use crate::visitors::for_each_expr; +use crate::{clip, is_ctor_or_promotable_const_function, is_direct_expn_of, path_res, sext, unsext}; use if_chain::if_chain; use rustc_ast::ast::{self, LitFloatType, LitKind}; use rustc_data_structures::sync::Lrc; @@ -17,6 +18,7 @@ use rustc_span::SyntaxContext; use std::cmp::Ordering::{self, Equal}; use std::hash::{Hash, Hasher}; use std::iter; +use std::ops::ControlFlow; /// A `LitKind`-like enum to fold constant `Expr`s into. #[derive(Debug, Clone)] @@ -736,3 +738,29 @@ fn field_of_struct<'tcx>( None } } + +/// Returns whether a certain `Expr` will be promoted to a constant. +pub fn is_promotable<'tcx>(cx: &LateContext<'tcx>, start: &'tcx Expr<'tcx>) -> bool { + let ty = cx.typeck_results().expr_ty(start); + for_each_expr(start, |expr| { + match expr.kind { + ExprKind::Binary(_, _, _) => ControlFlow::Break(()), + ExprKind::Unary(UnOp::Deref, e) if !matches!(path_res(cx, e), Res::Def(DefKind::Const, _)) => { + ControlFlow::Break(()) + }, + ExprKind::Call(_, _) if !is_ctor_or_promotable_const_function(cx, expr) => ControlFlow::Break(()), + ExprKind::MethodCall(..) if let Some(def_id) = cx.typeck_results().type_dependent_def_id(expr.hir_id) + && !cx.tcx.is_promotable_const_fn(def_id) => + { + ControlFlow::Break(()) + }, + ExprKind::Path(qpath) if let Res::Local(_) = cx.qpath_res(&qpath, expr.hir_id) => { + ControlFlow::Break(()) + }, + _ => ControlFlow::Continue(()), + } + }) + .is_none() + && ty.is_freeze(cx.tcx, cx.param_env) + && !ty.needs_drop(cx.tcx, cx.param_env) +} diff --git a/clippy_utils/src/lib.rs b/clippy_utils/src/lib.rs index cf33076d356d..4b12238983f6 100644 --- a/clippy_utils/src/lib.rs +++ b/clippy_utils/src/lib.rs @@ -2458,6 +2458,16 @@ pub fn is_test_module_or_function(tcx: TyCtxt<'_>, item: &Item<'_>) -> bool { && item.ident.name.as_str().split('_').any(|a| a == "test" || a == "tests") } +/// Returns whether `expr` is a temporary value that will be freed at the end of the statement. +pub fn is_temporary(cx: &LateContext<'_>, expr: &Expr<'_>) -> bool { + !expr.is_place_expr(|base| { + cx.typeck_results() + .adjustments() + .get(base.hir_id) + .is_some_and(|x| x.iter().any(|adj| matches!(adj.kind, Adjust::Deref(_)))) + }) +} + /// Walks the HIR tree from the given expression, up to the node where the value produced by the /// expression is consumed. Calls the function for every node encountered this way until it returns /// `Some`. diff --git a/clippy_utils/src/mir/mod.rs b/clippy_utils/src/mir/mod.rs index 131f3c0aa394..b43f04434486 100644 --- a/clippy_utils/src/mir/mod.rs +++ b/clippy_utils/src/mir/mod.rs @@ -1,7 +1,8 @@ use rustc_hir::{Expr, HirId}; use rustc_middle::mir::visit::{MutatingUseContext, NonMutatingUseContext, PlaceContext, Visitor}; use rustc_middle::mir::{ - traversal, Body, InlineAsmOperand, Local, Location, Place, StatementKind, TerminatorKind, START_BLOCK, + traversal, Body, InlineAsmOperand, Local, Location, Place, Statement, StatementKind, Terminator, TerminatorKind, + START_BLOCK, }; use rustc_middle::ty::TyCtxt; @@ -165,3 +166,20 @@ fn is_local_assignment(mir: &Body<'_>, local: Local, location: Location) -> bool } } } + +/// Gets the statement or terminator this `Location` points to. +pub fn location_to_node<'a, 'tcx>(body: &'tcx Body<'tcx>, loc: Location) -> StatementOrTerminator<'a, 'tcx> { + let data = &body.basic_blocks[loc.block]; + + if data.statements.len() == loc.statement_index { + StatementOrTerminator::Terminator(data.terminator()) + } else { + StatementOrTerminator::Statement(&data.statements[loc.statement_index]) + } +} + +#[derive(Debug)] +pub enum StatementOrTerminator<'a, 'tcx> { + Statement(&'a Statement<'tcx>), + Terminator(&'a Terminator<'tcx>), +} diff --git a/tests/ui/borrow_deref_ref.fixed b/tests/ui/borrow_deref_ref.fixed index b951ba04c37f..875a8d9a8152 100644 --- a/tests/ui/borrow_deref_ref.fixed +++ b/tests/ui/borrow_deref_ref.fixed @@ -1,7 +1,7 @@ //@run-rustfix //@aux-build: proc_macros.rs:proc-macro -#![allow(dead_code, unused_variables)] +#![allow(clippy::ptr_to_temporary, dead_code, unused_variables)] extern crate proc_macros; use proc_macros::with_span; diff --git a/tests/ui/borrow_deref_ref.rs b/tests/ui/borrow_deref_ref.rs index 52980e55fbea..b6438aae145c 100644 --- a/tests/ui/borrow_deref_ref.rs +++ b/tests/ui/borrow_deref_ref.rs @@ -1,7 +1,7 @@ //@run-rustfix //@aux-build: proc_macros.rs:proc-macro -#![allow(dead_code, unused_variables)] +#![allow(clippy::ptr_to_temporary, dead_code, unused_variables)] extern crate proc_macros; use proc_macros::with_span; diff --git a/tests/ui/cast_alignment.rs b/tests/ui/cast_alignment.rs index 95bb883df1bf..5dd4f05d3bb6 100644 --- a/tests/ui/cast_alignment.rs +++ b/tests/ui/cast_alignment.rs @@ -9,7 +9,8 @@ extern crate libc; clippy::no_effect, clippy::unnecessary_operation, clippy::cast_lossless, - clippy::borrow_as_ptr + clippy::borrow_as_ptr, + clippy::ptr_to_temporary )] fn main() { diff --git a/tests/ui/cast_alignment.stderr b/tests/ui/cast_alignment.stderr index 5df2b5b1094b..b0a1f979c5e3 100644 --- a/tests/ui/cast_alignment.stderr +++ b/tests/ui/cast_alignment.stderr @@ -1,5 +1,5 @@ error: casting from `*const u8` to a more-strictly-aligned pointer (`*const u16`) (1 < 2 bytes) - --> $DIR/cast_alignment.rs:19:5 + --> $DIR/cast_alignment.rs:20:5 | LL | (&1u8 as *const u8) as *const u16; | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ @@ -7,19 +7,19 @@ LL | (&1u8 as *const u8) as *const u16; = note: `-D clippy::cast-ptr-alignment` implied by `-D warnings` error: casting from `*mut u8` to a more-strictly-aligned pointer (`*mut u16`) (1 < 2 bytes) - --> $DIR/cast_alignment.rs:20:5 + --> $DIR/cast_alignment.rs:21:5 | LL | (&mut 1u8 as *mut u8) as *mut u16; | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ error: casting from `*const u8` to a more-strictly-aligned pointer (`*const u16`) (1 < 2 bytes) - --> $DIR/cast_alignment.rs:23:5 + --> $DIR/cast_alignment.rs:24:5 | LL | (&1u8 as *const u8).cast::(); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ error: casting from `*mut u8` to a more-strictly-aligned pointer (`*mut u16`) (1 < 2 bytes) - --> $DIR/cast_alignment.rs:24:5 + --> $DIR/cast_alignment.rs:25:5 | LL | (&mut 1u8 as *mut u8).cast::(); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ diff --git a/tests/ui/ptr_to_temporary.rs b/tests/ui/ptr_to_temporary.rs new file mode 100644 index 000000000000..f603d7f21984 --- /dev/null +++ b/tests/ui/ptr_to_temporary.rs @@ -0,0 +1,186 @@ +//@aux-build:proc_macros.rs:proc-macro +#![allow( + clippy::borrow_deref_ref, + clippy::deref_addrof, + clippy::identity_op, + clippy::unnecessary_cast, + clippy::unnecessary_operation, + temporary_cstring_as_ptr, + unused +)] +#![warn(clippy::ptr_to_temporary)] +#![no_main] + +#[macro_use] +extern crate proc_macros; + +use std::cell::{Cell, RefCell}; +use std::ffi::CString; +use std::sync::atomic::AtomicBool; + +fn bad_1() -> *const i32 { + // NOTE: `is_const_evaluatable` misses this. This may be a bug in that utils function, and if + // possible we should switch to it. + &(100 + *&0) as *const i32 +} + +fn bad_2() -> *const i32 { + let a = 0i32; + &(*&a) as *const i32 +} + +fn bad_3() -> *const i32 { + let a = 0i32; + &a as *const i32 +} + +fn bad_4() -> *const i32 { + let mut a = 0i32; + &a as *const i32 +} + +fn bad_5() -> *const i32 { + const A: &i32 = &1i32; + let mut a = 0i32; + + if true { + return &(*A) as *const i32; + } + &a as *const i32 +} + +fn bad_6() { + let pv = vec![1].as_ptr(); +} + +fn bad_7() { + fn helper() -> [i32; 1] { + [1] + } + + let pa = helper().as_ptr(); +} + +fn bad_8() { + let pc = Cell::new("oops ub").as_ptr(); +} + +fn bad_9() { + let prc = RefCell::new("oops more ub").as_ptr(); +} + +fn bad_10() { + // Our lint and `temporary_cstring_as_ptr` both catch this. Maybe we can deprecate that one? + let pcstr = unsafe { CString::new(vec![]).unwrap().as_ptr() }; +} + +fn bad_11() { + let pab = unsafe { AtomicBool::new(true).as_ptr() }; +} + +fn bad_12() { + let ps = vec![1].as_slice().as_ptr(); +} + +fn bad_13() { + let ps = <[i32]>::as_ptr(Vec::as_slice(&vec![1])); +} + +fn bad_14() { + CString::new("asd".to_owned()).unwrap().as_c_str().as_ptr(); +} + +fn bad_15() { + let pv = (*vec![12].into_boxed_slice()).as_ptr(); +} + +fn bad_16() { + let pv = vec![12].into_boxed_slice().as_ptr(); +} + +fn bad_17() { + [1u8, 2].as_mut_ptr(); +} + +// TODO: We need more tests here... + +fn fine_1() -> *const i32 { + &100 as *const i32 +} + +fn fine_2() -> *const i32 { + const A: &i32 = &0i32; + A as *const i32 +} + +fn fine_3() -> *const i32 { + const A: &i32 = &0i32; + &(*A) as *const i32 +} + +fn fine_4() { + let pa = ([1],).0.as_ptr(); +} + +fn fine_5() { + fn helper() -> &'static str { + "i'm not ub" + } + + let ps = helper().as_ptr(); +} + +fn fine_6() { + fn helper<'a>() -> &'a str { + "i'm not ub" + } + + let ps = helper().as_ptr(); +} + +fn fine_7() { + fn helper() -> &'static [i32; 1] { + &[1] + } + + let pa = helper().as_ptr(); +} + +fn fine_8() { + let ps = "a".as_ptr(); +} + +fn fine_9() { + let pcstr = CString::new("asd".to_owned()).unwrap(); + // Not UB, as `pcstr` is not a temporary + pcstr.as_c_str().as_ptr(); +} + +fn fine_10() { + let pcstr = CString::new("asd".to_owned()).unwrap(); + // Not UB, as `pcstr` is not a temporary + CString::as_c_str(&pcstr).as_ptr(); +} + +// Should still lint + +external! { + fn bad_external() -> *const i32 { + let a = 0i32; + &a as *const i32 + } + fn bad_external_2() { + let ps = <[i32]>::as_ptr(Vec::as_slice(&vec![1])); + } +} + +with_span! { + span + fn bad_proc_macro() -> *const i32 { + let a = 0i32; + &a as *const i32 + } + fn bad_proc_macro_2() { + let ps = <[i32]>::as_ptr(Vec::as_slice(&vec![1])); + } +} diff --git a/tests/ui/ptr_to_temporary.stderr b/tests/ui/ptr_to_temporary.stderr new file mode 100644 index 000000000000..55dd7cf2029a --- /dev/null +++ b/tests/ui/ptr_to_temporary.stderr @@ -0,0 +1,185 @@ +error: returning a raw pointer to a temporary value that cannot be promoted to a constant + --> $DIR/ptr_to_temporary.rs:24:5 + | +LL | &(100 + *&0) as *const i32 + | ^^^^^^^^^^^^^^^^^^^^^^^^^^ + | + = note: usage of this pointer by callers will cause Undefined Behavior as the temporary will be deallocated at the end of the statement, yet the pointer will continue pointing to it, resulting in a dangling pointer + = note: `-D clippy::ptr-to-temporary` implied by `-D warnings` + +error: returning a raw pointer to a temporary value that cannot be promoted to a constant + --> $DIR/ptr_to_temporary.rs:29:5 + | +LL | &(*&a) as *const i32 + | ^^^^^^^^^^^^^^^^^^^^ + | + = note: usage of this pointer by callers will cause Undefined Behavior as the temporary will be deallocated at the end of the statement, yet the pointer will continue pointing to it, resulting in a dangling pointer + +error: returning a raw pointer to a temporary value that cannot be promoted to a constant + --> $DIR/ptr_to_temporary.rs:34:5 + | +LL | &a as *const i32 + | ^^^^^^^^^^^^^^^^ + | + = note: usage of this pointer by callers will cause Undefined Behavior as the temporary will be deallocated at the end of the statement, yet the pointer will continue pointing to it, resulting in a dangling pointer + +error: returning a raw pointer to a temporary value that cannot be promoted to a constant + --> $DIR/ptr_to_temporary.rs:39:5 + | +LL | &a as *const i32 + | ^^^^^^^^^^^^^^^^ + | + = note: usage of this pointer by callers will cause Undefined Behavior as the temporary will be deallocated at the end of the statement, yet the pointer will continue pointing to it, resulting in a dangling pointer + +error: returning a raw pointer to a temporary value that cannot be promoted to a constant + --> $DIR/ptr_to_temporary.rs:49:5 + | +LL | &a as *const i32 + | ^^^^^^^^^^^^^^^^ + | + = note: usage of this pointer by callers will cause Undefined Behavior as the temporary will be deallocated at the end of the statement, yet the pointer will continue pointing to it, resulting in a dangling pointer + +error: calling `as_ptr` on a temporary value + --> $DIR/ptr_to_temporary.rs:53:14 + | +LL | let pv = vec![1].as_ptr(); + | ^^^^^^^^^^^^^^^^ + | + = note: usage of this pointer will cause Undefined Behavior as the temporary will be deallocated at the end of the statement, yet the pointer will continue pointing to it, resulting in a dangling pointer + +error: calling `as_ptr` on a temporary value + --> $DIR/ptr_to_temporary.rs:61:14 + | +LL | let pa = helper().as_ptr(); + | ^^^^^^^^^^^^^^^^^ + | + = note: usage of this pointer will cause Undefined Behavior as the temporary will be deallocated at the end of the statement, yet the pointer will continue pointing to it, resulting in a dangling pointer + +error: calling `as_ptr` on a temporary value + --> $DIR/ptr_to_temporary.rs:65:14 + | +LL | let pc = Cell::new("oops ub").as_ptr(); + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + | + = note: usage of this pointer will cause Undefined Behavior as the temporary will be deallocated at the end of the statement, yet the pointer will continue pointing to it, resulting in a dangling pointer + +error: calling `as_ptr` on a temporary value + --> $DIR/ptr_to_temporary.rs:69:15 + | +LL | let prc = RefCell::new("oops more ub").as_ptr(); + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + | + = note: usage of this pointer will cause Undefined Behavior as the temporary will be deallocated at the end of the statement, yet the pointer will continue pointing to it, resulting in a dangling pointer + +error: calling `as_ptr` on a temporary value + --> $DIR/ptr_to_temporary.rs:74:26 + | +LL | let pcstr = unsafe { CString::new(vec![]).unwrap().as_ptr() }; + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + | + = note: usage of this pointer will cause Undefined Behavior as the temporary will be deallocated at the end of the statement, yet the pointer will continue pointing to it, resulting in a dangling pointer + +error: calling `as_ptr` on a temporary value + --> $DIR/ptr_to_temporary.rs:78:24 + | +LL | let pab = unsafe { AtomicBool::new(true).as_ptr() }; + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + | + = note: usage of this pointer will cause Undefined Behavior as the temporary will be deallocated at the end of the statement, yet the pointer will continue pointing to it, resulting in a dangling pointer + +error: calling `as_ptr` on a temporary value + --> $DIR/ptr_to_temporary.rs:82:14 + | +LL | let ps = vec![1].as_slice().as_ptr(); + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^ + | + = note: usage of this pointer will cause Undefined Behavior as the temporary will be deallocated at the end of the statement, yet the pointer will continue pointing to it, resulting in a dangling pointer + +error: calling `as_ptr` on a temporary value + --> $DIR/ptr_to_temporary.rs:86:14 + | +LL | let ps = <[i32]>::as_ptr(Vec::as_slice(&vec![1])); + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + | + = note: usage of this pointer will cause Undefined Behavior as the temporary will be deallocated at the end of the statement, yet the pointer will continue pointing to it, resulting in a dangling pointer + +error: calling `as_ptr` on a temporary value + --> $DIR/ptr_to_temporary.rs:90:5 + | +LL | CString::new("asd".to_owned()).unwrap().as_c_str().as_ptr(); + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + | + = note: usage of this pointer will cause Undefined Behavior as the temporary will be deallocated at the end of the statement, yet the pointer will continue pointing to it, resulting in a dangling pointer + +error: calling `as_ptr` on a temporary value + --> $DIR/ptr_to_temporary.rs:94:14 + | +LL | let pv = (*vec![12].into_boxed_slice()).as_ptr(); + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + | + = note: usage of this pointer will cause Undefined Behavior as the temporary will be deallocated at the end of the statement, yet the pointer will continue pointing to it, resulting in a dangling pointer + +error: calling `as_ptr` on a temporary value + --> $DIR/ptr_to_temporary.rs:98:14 + | +LL | let pv = vec![12].into_boxed_slice().as_ptr(); + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + | + = note: usage of this pointer will cause Undefined Behavior as the temporary will be deallocated at the end of the statement, yet the pointer will continue pointing to it, resulting in a dangling pointer + +error: calling `as_mut_ptr` on a temporary value + --> $DIR/ptr_to_temporary.rs:102:5 + | +LL | [1u8, 2].as_mut_ptr(); + | ^^^^^^^^^^^^^^^^^^^^^ + | + = note: usage of this pointer will cause Undefined Behavior as the temporary will be deallocated at the end of the statement, yet the pointer will continue pointing to it, resulting in a dangling pointer + +error: returning a raw pointer to a temporary value that cannot be promoted to a constant + --> $DIR/ptr_to_temporary.rs:167:1 + | +LL | / external! { +LL | | fn bad_external() -> *const i32 { +LL | | let a = 0i32; +LL | | &a as *const i32 +... | +LL | | } +LL | | } + | |_^ + | + = note: usage of this pointer by callers will cause Undefined Behavior as the temporary will be deallocated at the end of the statement, yet the pointer will continue pointing to it, resulting in a dangling pointer + = note: this error originates in the macro `external` (in Nightly builds, run with -Z macro-backtrace for more info) + +error: calling `as_ptr` on a temporary value + --> $DIR/ptr_to_temporary.rs:167:1 + | +LL | / external! { +LL | | fn bad_external() -> *const i32 { +LL | | let a = 0i32; +LL | | &a as *const i32 +... | +LL | | } +LL | | } + | |_^ + | + = note: usage of this pointer will cause Undefined Behavior as the temporary will be deallocated at the end of the statement, yet the pointer will continue pointing to it, resulting in a dangling pointer + = note: this error originates in the macro `external` (in Nightly builds, run with -Z macro-backtrace for more info) + +error: returning a raw pointer to a temporary value that cannot be promoted to a constant + --> $DIR/ptr_to_temporary.rs:178:5 + | +LL | span + | ^^^^ + | + = note: usage of this pointer by callers will cause Undefined Behavior as the temporary will be deallocated at the end of the statement, yet the pointer will continue pointing to it, resulting in a dangling pointer + +error: calling `as_ptr` on a temporary value + --> $DIR/ptr_to_temporary.rs:178:5 + | +LL | span + | ^^^^ + | + = note: usage of this pointer will cause Undefined Behavior as the temporary will be deallocated at the end of the statement, yet the pointer will continue pointing to it, resulting in a dangling pointer + +error: aborting due to 21 previous errors + diff --git a/tests/ui/transmute_ptr_to_ptr.rs b/tests/ui/transmute_ptr_to_ptr.rs index 61a6c98ed5ac..d678087a128f 100644 --- a/tests/ui/transmute_ptr_to_ptr.rs +++ b/tests/ui/transmute_ptr_to_ptr.rs @@ -1,5 +1,5 @@ #![warn(clippy::transmute_ptr_to_ptr)] -#![allow(clippy::borrow_as_ptr)] +#![allow(clippy::borrow_as_ptr, clippy::ptr_to_temporary)] // Make sure we can modify lifetimes, which is one of the recommended uses // of transmute diff --git a/tests/ui/transmutes_expressible_as_ptr_casts.fixed b/tests/ui/transmutes_expressible_as_ptr_casts.fixed index 05aa86c479ad..4ca005da4859 100644 --- a/tests/ui/transmutes_expressible_as_ptr_casts.fixed +++ b/tests/ui/transmutes_expressible_as_ptr_casts.fixed @@ -4,7 +4,7 @@ // would otherwise be responsible for #![warn(clippy::useless_transmute)] #![warn(clippy::transmute_ptr_to_ptr)] -#![allow(unused, clippy::borrow_as_ptr)] +#![allow(unused, clippy::borrow_as_ptr, clippy::ptr_to_temporary)] use std::mem::{size_of, transmute}; diff --git a/tests/ui/transmutes_expressible_as_ptr_casts.rs b/tests/ui/transmutes_expressible_as_ptr_casts.rs index 29fa6914cfd0..4c3d2eca1770 100644 --- a/tests/ui/transmutes_expressible_as_ptr_casts.rs +++ b/tests/ui/transmutes_expressible_as_ptr_casts.rs @@ -4,7 +4,7 @@ // would otherwise be responsible for #![warn(clippy::useless_transmute)] #![warn(clippy::transmute_ptr_to_ptr)] -#![allow(unused, clippy::borrow_as_ptr)] +#![allow(unused, clippy::borrow_as_ptr, clippy::ptr_to_temporary)] use std::mem::{size_of, transmute}; diff --git a/tests/ui/unnecessary_cast.fixed b/tests/ui/unnecessary_cast.fixed index 2bf02f134142..a108f7306968 100644 --- a/tests/ui/unnecessary_cast.fixed +++ b/tests/ui/unnecessary_cast.fixed @@ -5,6 +5,7 @@ clippy::borrow_as_ptr, clippy::no_effect, clippy::nonstandard_macro_braces, + clippy::ptr_to_temporary, clippy::unnecessary_operation, nonstandard_style, unused diff --git a/tests/ui/unnecessary_cast.rs b/tests/ui/unnecessary_cast.rs index 25b6b0f9b07b..5c0e249b0d2b 100644 --- a/tests/ui/unnecessary_cast.rs +++ b/tests/ui/unnecessary_cast.rs @@ -5,6 +5,7 @@ clippy::borrow_as_ptr, clippy::no_effect, clippy::nonstandard_macro_braces, + clippy::ptr_to_temporary, clippy::unnecessary_operation, nonstandard_style, unused diff --git a/tests/ui/unnecessary_cast.stderr b/tests/ui/unnecessary_cast.stderr index 19411a01b67d..c92488b8e506 100644 --- a/tests/ui/unnecessary_cast.stderr +++ b/tests/ui/unnecessary_cast.stderr @@ -1,5 +1,5 @@ error: casting raw pointers to the same type and constness is unnecessary (`*const T` -> `*const T`) - --> $DIR/unnecessary_cast.rs:19:5 + --> $DIR/unnecessary_cast.rs:20:5 | LL | ptr as *const T | ^^^^^^^^^^^^^^^ help: try: `ptr` @@ -7,235 +7,235 @@ LL | ptr as *const T = note: `-D clippy::unnecessary-cast` implied by `-D warnings` error: casting integer literal to `i32` is unnecessary - --> $DIR/unnecessary_cast.rs:54:5 + --> $DIR/unnecessary_cast.rs:55:5 | LL | 1i32 as i32; | ^^^^^^^^^^^ help: try: `1_i32` error: casting float literal to `f32` is unnecessary - --> $DIR/unnecessary_cast.rs:55:5 + --> $DIR/unnecessary_cast.rs:56:5 | LL | 1f32 as f32; | ^^^^^^^^^^^ help: try: `1_f32` error: casting to the same type is unnecessary (`bool` -> `bool`) - --> $DIR/unnecessary_cast.rs:56:5 + --> $DIR/unnecessary_cast.rs:57:5 | LL | false as bool; | ^^^^^^^^^^^^^ help: try: `false` error: casting integer literal to `i32` is unnecessary - --> $DIR/unnecessary_cast.rs:59:5 + --> $DIR/unnecessary_cast.rs:60:5 | LL | -1_i32 as i32; | ^^^^^^^^^^^^^ help: try: `-1_i32` error: casting integer literal to `i32` is unnecessary - --> $DIR/unnecessary_cast.rs:60:5 + --> $DIR/unnecessary_cast.rs:61:5 | LL | - 1_i32 as i32; | ^^^^^^^^^^^^^^ help: try: `- 1_i32` error: casting float literal to `f32` is unnecessary - --> $DIR/unnecessary_cast.rs:61:5 + --> $DIR/unnecessary_cast.rs:62:5 | LL | -1f32 as f32; | ^^^^^^^^^^^^ help: try: `-1_f32` error: casting integer literal to `i32` is unnecessary - --> $DIR/unnecessary_cast.rs:62:5 + --> $DIR/unnecessary_cast.rs:63:5 | LL | 1_i32 as i32; | ^^^^^^^^^^^^ help: try: `1_i32` error: casting float literal to `f32` is unnecessary - --> $DIR/unnecessary_cast.rs:63:5 + --> $DIR/unnecessary_cast.rs:64:5 | LL | 1_f32 as f32; | ^^^^^^^^^^^^ help: try: `1_f32` error: casting raw pointers to the same type and constness is unnecessary (`*const u8` -> `*const u8`) - --> $DIR/unnecessary_cast.rs:65:22 + --> $DIR/unnecessary_cast.rs:66:22 | LL | let _: *mut u8 = [1u8, 2].as_ptr() as *const u8 as *mut u8; | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: try: `[1u8, 2].as_ptr()` error: casting raw pointers to the same type and constness is unnecessary (`*const u8` -> `*const u8`) - --> $DIR/unnecessary_cast.rs:67:5 + --> $DIR/unnecessary_cast.rs:68:5 | LL | [1u8, 2].as_ptr() as *const u8; | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: try: `[1u8, 2].as_ptr()` error: casting raw pointers to the same type and constness is unnecessary (`*mut u8` -> `*mut u8`) - --> $DIR/unnecessary_cast.rs:69:5 + --> $DIR/unnecessary_cast.rs:70:5 | LL | [1u8, 2].as_mut_ptr() as *mut u8; | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: try: `[1u8, 2].as_mut_ptr()` error: casting raw pointers to the same type and constness is unnecessary (`*const u32` -> `*const u32`) - --> $DIR/unnecessary_cast.rs:80:5 + --> $DIR/unnecessary_cast.rs:81:5 | LL | owo::([1u32].as_ptr()) as *const u32; | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: try: `owo::([1u32].as_ptr())` error: casting raw pointers to the same type and constness is unnecessary (`*const u8` -> `*const u8`) - --> $DIR/unnecessary_cast.rs:81:5 + --> $DIR/unnecessary_cast.rs:82:5 | LL | uwu::([1u32].as_ptr()) as *const u8; | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: try: `uwu::([1u32].as_ptr())` error: casting raw pointers to the same type and constness is unnecessary (`*const u32` -> `*const u32`) - --> $DIR/unnecessary_cast.rs:83:5 + --> $DIR/unnecessary_cast.rs:84:5 | LL | uwu::([1u32].as_ptr()) as *const u32; | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: try: `uwu::([1u32].as_ptr())` error: casting to the same type is unnecessary (`u32` -> `u32`) - --> $DIR/unnecessary_cast.rs:118:5 + --> $DIR/unnecessary_cast.rs:119:5 | LL | aaa() as u32; | ^^^^^^^^^^^^ help: try: `aaa()` error: casting to the same type is unnecessary (`u32` -> `u32`) - --> $DIR/unnecessary_cast.rs:120:5 + --> $DIR/unnecessary_cast.rs:121:5 | LL | aaa() as u32; | ^^^^^^^^^^^^ help: try: `aaa()` error: casting integer literal to `f32` is unnecessary - --> $DIR/unnecessary_cast.rs:156:9 + --> $DIR/unnecessary_cast.rs:157:9 | LL | 100 as f32; | ^^^^^^^^^^ help: try: `100_f32` error: casting integer literal to `f64` is unnecessary - --> $DIR/unnecessary_cast.rs:157:9 + --> $DIR/unnecessary_cast.rs:158:9 | LL | 100 as f64; | ^^^^^^^^^^ help: try: `100_f64` error: casting integer literal to `f64` is unnecessary - --> $DIR/unnecessary_cast.rs:158:9 + --> $DIR/unnecessary_cast.rs:159:9 | LL | 100_i32 as f64; | ^^^^^^^^^^^^^^ help: try: `100_f64` error: casting integer literal to `f32` is unnecessary - --> $DIR/unnecessary_cast.rs:159:17 + --> $DIR/unnecessary_cast.rs:160:17 | LL | let _ = -100 as f32; | ^^^^^^^^^^^ help: try: `-100_f32` error: casting integer literal to `f64` is unnecessary - --> $DIR/unnecessary_cast.rs:160:17 + --> $DIR/unnecessary_cast.rs:161:17 | LL | let _ = -100 as f64; | ^^^^^^^^^^^ help: try: `-100_f64` error: casting integer literal to `f64` is unnecessary - --> $DIR/unnecessary_cast.rs:161:17 + --> $DIR/unnecessary_cast.rs:162:17 | LL | let _ = -100_i32 as f64; | ^^^^^^^^^^^^^^^ help: try: `-100_f64` error: casting float literal to `f32` is unnecessary - --> $DIR/unnecessary_cast.rs:162:9 + --> $DIR/unnecessary_cast.rs:163:9 | LL | 100. as f32; | ^^^^^^^^^^^ help: try: `100_f32` error: casting float literal to `f64` is unnecessary - --> $DIR/unnecessary_cast.rs:163:9 + --> $DIR/unnecessary_cast.rs:164:9 | LL | 100. as f64; | ^^^^^^^^^^^ help: try: `100_f64` error: casting integer literal to `u32` is unnecessary - --> $DIR/unnecessary_cast.rs:175:9 + --> $DIR/unnecessary_cast.rs:176:9 | LL | 1 as u32; | ^^^^^^^^ help: try: `1_u32` error: casting integer literal to `i32` is unnecessary - --> $DIR/unnecessary_cast.rs:176:9 + --> $DIR/unnecessary_cast.rs:177:9 | LL | 0x10 as i32; | ^^^^^^^^^^^ help: try: `0x10_i32` error: casting integer literal to `usize` is unnecessary - --> $DIR/unnecessary_cast.rs:177:9 + --> $DIR/unnecessary_cast.rs:178:9 | LL | 0b10 as usize; | ^^^^^^^^^^^^^ help: try: `0b10_usize` error: casting integer literal to `u16` is unnecessary - --> $DIR/unnecessary_cast.rs:178:9 + --> $DIR/unnecessary_cast.rs:179:9 | LL | 0o73 as u16; | ^^^^^^^^^^^ help: try: `0o73_u16` error: casting integer literal to `u32` is unnecessary - --> $DIR/unnecessary_cast.rs:179:9 + --> $DIR/unnecessary_cast.rs:180:9 | LL | 1_000_000_000 as u32; | ^^^^^^^^^^^^^^^^^^^^ help: try: `1_000_000_000_u32` error: casting float literal to `f64` is unnecessary - --> $DIR/unnecessary_cast.rs:181:9 + --> $DIR/unnecessary_cast.rs:182:9 | LL | 1.0 as f64; | ^^^^^^^^^^ help: try: `1.0_f64` error: casting float literal to `f32` is unnecessary - --> $DIR/unnecessary_cast.rs:182:9 + --> $DIR/unnecessary_cast.rs:183:9 | LL | 0.5 as f32; | ^^^^^^^^^^ help: try: `0.5_f32` error: casting integer literal to `i32` is unnecessary - --> $DIR/unnecessary_cast.rs:186:17 + --> $DIR/unnecessary_cast.rs:187:17 | LL | let _ = -1 as i32; | ^^^^^^^^^ help: try: `-1_i32` error: casting float literal to `f32` is unnecessary - --> $DIR/unnecessary_cast.rs:187:17 + --> $DIR/unnecessary_cast.rs:188:17 | LL | let _ = -1.0 as f32; | ^^^^^^^^^^^ help: try: `-1.0_f32` error: casting to the same type is unnecessary (`i32` -> `i32`) - --> $DIR/unnecessary_cast.rs:193:18 + --> $DIR/unnecessary_cast.rs:194:18 | LL | let _ = &(x as i32); | ^^^^^^^^^^ help: try: `{ x }` error: casting integer literal to `i32` is unnecessary - --> $DIR/unnecessary_cast.rs:199:22 + --> $DIR/unnecessary_cast.rs:200:22 | LL | let _: i32 = -(1) as i32; | ^^^^^^^^^^^ help: try: `-1_i32` error: casting integer literal to `i64` is unnecessary - --> $DIR/unnecessary_cast.rs:201:22 + --> $DIR/unnecessary_cast.rs:202:22 | LL | let _: i64 = -(1) as i64; | ^^^^^^^^^^^ help: try: `-1_i64` error: casting float literal to `f64` is unnecessary - --> $DIR/unnecessary_cast.rs:208:22 + --> $DIR/unnecessary_cast.rs:209:22 | LL | let _: f64 = (-8.0 as f64).exp(); | ^^^^^^^^^^^^^ help: try: `(-8.0_f64)` error: casting float literal to `f64` is unnecessary - --> $DIR/unnecessary_cast.rs:210:23 + --> $DIR/unnecessary_cast.rs:211:23 | LL | let _: f64 = -(8.0 as f64).exp(); // should suggest `-8.0_f64.exp()` here not to change code behavior | ^^^^^^^^^^^^ help: try: `8.0_f64` error: casting to the same type is unnecessary (`f32` -> `f32`) - --> $DIR/unnecessary_cast.rs:218:20 + --> $DIR/unnecessary_cast.rs:219:20 | LL | let _num = foo() as f32; | ^^^^^^^^^^^^ help: try: `foo()` diff --git a/tests/ui/unnecessary_struct_initialization.fixed b/tests/ui/unnecessary_struct_initialization.fixed index eae1271d1aa7..bd221d1e9f7c 100644 --- a/tests/ui/unnecessary_struct_initialization.fixed +++ b/tests/ui/unnecessary_struct_initialization.fixed @@ -1,6 +1,6 @@ //@run-rustfix -#![allow(clippy::incorrect_clone_impl_on_copy_type, unused)] +#![allow(clippy::incorrect_clone_impl_on_copy_type, clippy::ptr_to_temporary)] #![warn(clippy::unnecessary_struct_initialization)] struct S { diff --git a/tests/ui/unnecessary_struct_initialization.rs b/tests/ui/unnecessary_struct_initialization.rs index 4abd560f84be..d23aca0cd26b 100644 --- a/tests/ui/unnecessary_struct_initialization.rs +++ b/tests/ui/unnecessary_struct_initialization.rs @@ -1,6 +1,6 @@ //@run-rustfix -#![allow(clippy::incorrect_clone_impl_on_copy_type, unused)] +#![allow(clippy::incorrect_clone_impl_on_copy_type, clippy::ptr_to_temporary)] #![warn(clippy::unnecessary_struct_initialization)] struct S { diff --git a/tests/ui/zero_offset.rs b/tests/ui/zero_offset.rs index fd9ac1fa7663..6434fb11865a 100644 --- a/tests/ui/zero_offset.rs +++ b/tests/ui/zero_offset.rs @@ -1,4 +1,4 @@ -#[allow(clippy::borrow_as_ptr)] +#[allow(clippy::borrow_as_ptr, clippy::ptr_to_temporary)] fn main() { unsafe { let m = &mut () as *mut ();