1use rustc_ast::LitKind;
2use rustc_errors::Applicability;
3use rustc_hir::def::{DefKind, Res};
4use rustc_hir::def_id::LocalDefId;
5use rustc_hir::{self as hir};
6use rustc_macros::LintDiagnostic;
7use rustc_middle::ty::{self, Ty};
8use rustc_session::{declare_lint, impl_lint_pass};
9use rustc_span::sym;
10
11use crate::lints::{IntegerToPtrTransmutes, IntegerToPtrTransmutesSuggestion};
12use crate::{LateContext, LateLintPass};
13
14declare_lint! {
15 pub PTR_TO_INTEGER_TRANSMUTE_IN_CONSTS,
44 Warn,
45 "detects pointer to integer transmutes in const functions and associated constants",
46}
47
48declare_lint! {
49 pub UNNECESSARY_TRANSMUTES,
68 Warn,
69 "detects transmutes that can also be achieved by other operations"
70}
71
72declare_lint! {
73 pub INTEGER_TO_PTR_TRANSMUTES,
103 Warn,
104 "detects integer to pointer transmutes",
105}
106
107pub(crate) struct CheckTransmutes;
108
109impl_lint_pass!(CheckTransmutes => [PTR_TO_INTEGER_TRANSMUTE_IN_CONSTS, UNNECESSARY_TRANSMUTES, INTEGER_TO_PTR_TRANSMUTES]);
110
111impl<'tcx> LateLintPass<'tcx> for CheckTransmutes {
112 fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx hir::Expr<'tcx>) {
113 let hir::ExprKind::Call(callee, [arg]) = expr.kind else {
114 return;
115 };
116 let hir::ExprKind::Path(qpath) = callee.kind else {
117 return;
118 };
119 let Res::Def(DefKind::Fn, def_id) = cx.qpath_res(&qpath, callee.hir_id) else {
120 return;
121 };
122 if !cx.tcx.is_intrinsic(def_id, sym::transmute) {
123 return;
124 };
125 let body_owner_def_id = cx.tcx.hir_enclosing_body_owner(expr.hir_id);
126 let const_context = cx.tcx.hir_body_const_context(body_owner_def_id);
127 let args = cx.typeck_results().node_args(callee.hir_id);
128
129 let src = args.type_at(0);
130 let dst = args.type_at(1);
131
132 check_ptr_transmute_in_const(cx, expr, body_owner_def_id, const_context, src, dst);
133 check_unnecessary_transmute(cx, expr, callee, arg, const_context, src, dst);
134 check_int_to_ptr_transmute(cx, expr, arg, src, dst);
135 }
136}
137
138fn check_int_to_ptr_transmute<'tcx>(
142 cx: &LateContext<'tcx>,
143 expr: &'tcx hir::Expr<'tcx>,
144 arg: &'tcx hir::Expr<'tcx>,
145 src: Ty<'tcx>,
146 dst: Ty<'tcx>,
147) {
148 if !matches!(src.kind(), ty::Uint(_) | ty::Int(_)) {
149 return;
150 }
151 let (ty::Ref(_, inner_ty, mutbl) | ty::RawPtr(inner_ty, mutbl)) = dst.kind() else {
152 return;
153 };
154 if matches!(arg.kind, hir::ExprKind::Lit(hir::Lit { node: LitKind::Int(v, _), .. }) if v == 0) {
156 return;
157 }
158 let Ok(layout_inner_ty) = cx.tcx.layout_of(cx.typing_env().as_query_input(*inner_ty)) else {
160 return;
161 };
162 if layout_inner_ty.is_1zst() {
163 return;
164 }
165
166 let suffix = if mutbl.is_mut() { "_mut" } else { "" };
167 cx.tcx.emit_node_span_lint(
168 INTEGER_TO_PTR_TRANSMUTES,
169 expr.hir_id,
170 expr.span,
171 IntegerToPtrTransmutes {
172 suggestion: if dst.is_ref() {
173 IntegerToPtrTransmutesSuggestion::ToRef {
174 dst: *inner_ty,
175 suffix,
176 ref_mutbl: mutbl.prefix_str(),
177 start_call: expr.span.shrink_to_lo().until(arg.span),
178 }
179 } else {
180 IntegerToPtrTransmutesSuggestion::ToPtr {
181 dst: *inner_ty,
182 suffix,
183 start_call: expr.span.shrink_to_lo().until(arg.span),
184 }
185 },
186 },
187 );
188}
189
190fn check_ptr_transmute_in_const<'tcx>(
203 cx: &LateContext<'tcx>,
204 expr: &'tcx hir::Expr<'tcx>,
205 body_owner_def_id: LocalDefId,
206 const_context: Option<hir::ConstContext>,
207 src: Ty<'tcx>,
208 dst: Ty<'tcx>,
209) {
210 if matches!(const_context, Some(hir::ConstContext::ConstFn))
211 || matches!(cx.tcx.def_kind(body_owner_def_id), DefKind::AssocConst)
212 {
213 if src.is_raw_ptr() && dst.is_integral() {
214 cx.tcx.emit_node_span_lint(
215 PTR_TO_INTEGER_TRANSMUTE_IN_CONSTS,
216 expr.hir_id,
217 expr.span,
218 UndefinedTransmuteLint,
219 );
220 }
221 }
222}
223
224fn check_unnecessary_transmute<'tcx>(
229 cx: &LateContext<'tcx>,
230 expr: &'tcx hir::Expr<'tcx>,
231 callee: &'tcx hir::Expr<'tcx>,
232 arg: &'tcx hir::Expr<'tcx>,
233 const_context: Option<hir::ConstContext>,
234 src: Ty<'tcx>,
235 dst: Ty<'tcx>,
236) {
237 let callee_span = callee.span.find_ancestor_inside(expr.span).unwrap_or(callee.span);
238 let (sugg, help) = match (src.kind(), dst.kind()) {
239 (ty::Array(t, _), ty::Uint(_) | ty::Float(_) | ty::Int(_))
242 if *t.kind() == ty::Uint(ty::UintTy::U8) =>
243 {
244 (
245 Some(vec![(callee_span, format!("{dst}::from_ne_bytes"))]),
246 Some(
247 "there's also `from_le_bytes` and `from_be_bytes` if you expect a particular byte order",
248 ),
249 )
250 }
251 (ty::Uint(_) | ty::Float(_) | ty::Int(_), ty::Array(t, _))
253 if *t.kind() == ty::Uint(ty::UintTy::U8) =>
254 {
255 (
256 Some(vec![(callee_span, format!("{src}::to_ne_bytes"))]),
257 Some(
258 "there's also `to_le_bytes` and `to_be_bytes` if you expect a particular byte order",
259 ),
260 )
261 }
262 (ty::Char, ty::Uint(ty::UintTy::U32)) => {
264 (Some(vec![(callee_span, "u32::from".to_string())]), None)
265 }
266 (ty::Char, ty::Int(ty::IntTy::I32)) => (
268 Some(vec![
269 (callee_span, "u32::from".to_string()),
270 (expr.span.shrink_to_hi(), ".cast_signed()".to_string()),
271 ]),
272 None,
273 ),
274 (ty::Uint(ty::UintTy::U32), ty::Char) => (
276 Some(vec![(callee_span, "char::from_u32_unchecked".to_string())]),
277 Some("consider using `char::from_u32(…).unwrap()`"),
278 ),
279 (ty::Int(ty::IntTy::I32), ty::Char) => (
281 Some(vec![
282 (callee_span, "char::from_u32_unchecked(i32::cast_unsigned".to_string()),
283 (expr.span.shrink_to_hi(), ")".to_string()),
284 ]),
285 Some("consider using `char::from_u32(i32::cast_unsigned(…)).unwrap()`"),
286 ),
287 (ty::Uint(_), ty::Int(_)) => {
289 (Some(vec![(callee_span, format!("{src}::cast_signed"))]), None)
290 }
291 (ty::Int(_), ty::Uint(_)) => {
293 (Some(vec![(callee_span, format!("{src}::cast_unsigned"))]), None)
294 }
295 (ty::Float(_), ty::Uint(ty::UintTy::Usize) | ty::Int(ty::IntTy::Isize)) => (
297 Some(vec![
298 (callee_span, format!("{src}::to_bits")),
299 (expr.span.shrink_to_hi(), format!(" as {dst}")),
300 ]),
301 None,
302 ),
303 (ty::Float(_), ty::Int(..)) => (
305 Some(vec![
306 (callee_span, format!("{src}::to_bits")),
307 (expr.span.shrink_to_hi(), ".cast_signed()".to_string()),
308 ]),
309 None,
310 ),
311 (ty::Float(_), ty::Uint(..)) => {
313 (Some(vec![(callee_span, format!("{src}::to_bits"))]), None)
314 }
315 (ty::Uint(ty::UintTy::Usize) | ty::Int(ty::IntTy::Isize), ty::Float(_)) => (
317 Some(vec![
318 (callee_span, format!("{dst}::from_bits")),
319 (arg.span.shrink_to_hi(), " as _".to_string()),
320 ]),
321 None,
322 ),
323 (ty::Int(_), ty::Float(_)) => (
325 Some(vec![
326 (callee_span, format!("{dst}::from_bits({src}::cast_unsigned")),
327 (expr.span.shrink_to_hi(), ")".to_string()),
328 ]),
329 None,
330 ),
331 (ty::Uint(_), ty::Float(_)) => {
333 (Some(vec![(callee_span, format!("{dst}::from_bits"))]), None)
334 }
335 (ty::Bool, ty::Int(..) | ty::Uint(..)) if const_context.is_some() => (
339 Some(vec![
340 (callee_span, "".to_string()),
341 (expr.span.shrink_to_hi(), format!(" as {dst}")),
342 ]),
343 None,
344 ),
345 (ty::Bool, ty::Int(..) | ty::Uint(..)) => {
347 (Some(vec![(callee_span, format!("{dst}::from"))]), None)
348 }
349 _ => return,
350 };
351
352 cx.tcx.node_span_lint(UNNECESSARY_TRANSMUTES, expr.hir_id, expr.span, |diag| {
353 diag.primary_message("unnecessary transmute");
354 if let Some(sugg) = sugg {
355 diag.multipart_suggestion("replace this with", sugg, Applicability::MachineApplicable);
356 }
357 if let Some(help) = help {
358 diag.help(help);
359 }
360 });
361}
362
363#[derive(LintDiagnostic)]
364#[diag(lint_undefined_transmute)]
365#[note]
366#[note(lint_note2)]
367#[help]
368pub(crate) struct UndefinedTransmuteLint;