1use std::borrow::Cow;
2use std::mem;
3use std::ops::Bound;
4
5use rustc_ast::AsmMacro;
6use rustc_data_structures::stack::ensure_sufficient_stack;
7use rustc_errors::DiagArgValue;
8use rustc_hir::def::DefKind;
9use rustc_hir::{self as hir, BindingMode, ByRef, HirId, Mutability, find_attr};
10use rustc_middle::middle::codegen_fn_attrs::{TargetFeature, TargetFeatureKind};
11use rustc_middle::mir::BorrowKind;
12use rustc_middle::span_bug;
13use rustc_middle::thir::visit::Visitor;
14use rustc_middle::thir::*;
15use rustc_middle::ty::print::with_no_trimmed_paths;
16use rustc_middle::ty::{self, Ty, TyCtxt};
17use rustc_session::lint::Level;
18use rustc_session::lint::builtin::{DEPRECATED_SAFE_2024, UNSAFE_OP_IN_UNSAFE_FN, UNUSED_UNSAFE};
19use rustc_span::def_id::{DefId, LocalDefId};
20use rustc_span::{Span, Symbol};
21
22use crate::builder::ExprCategory;
23use crate::errors::*;
24
25struct UnsafetyVisitor<'a, 'tcx> {
26 tcx: TyCtxt<'tcx>,
27 thir: &'a Thir<'tcx>,
28 hir_context: HirId,
31 safety_context: SafetyContext,
34 body_target_features: &'tcx [TargetFeature],
37 assignment_info: Option<Ty<'tcx>>,
40 in_union_destructure: bool,
41 typing_env: ty::TypingEnv<'tcx>,
42 inside_adt: bool,
43 warnings: &'a mut Vec<UnusedUnsafeWarning>,
44
45 suggest_unsafe_block: bool,
48}
49
50impl<'tcx> UnsafetyVisitor<'_, 'tcx> {
51 fn in_safety_context(&mut self, safety_context: SafetyContext, f: impl FnOnce(&mut Self)) {
52 let prev_context = mem::replace(&mut self.safety_context, safety_context);
53
54 f(self);
55
56 let safety_context = mem::replace(&mut self.safety_context, prev_context);
57 if let SafetyContext::UnsafeBlock { used, span, hir_id, nested_used_blocks } =
58 safety_context
59 {
60 if !used {
61 self.warn_unused_unsafe(hir_id, span, None);
62
63 if let SafetyContext::UnsafeBlock {
64 nested_used_blocks: ref mut prev_nested_used_blocks,
65 ..
66 } = self.safety_context
67 {
68 prev_nested_used_blocks.extend(nested_used_blocks);
69 }
70 } else {
71 for block in nested_used_blocks {
72 self.warn_unused_unsafe(
73 block.hir_id,
74 block.span,
75 Some(UnusedUnsafeEnclosing::Block {
76 span: self.tcx.sess.source_map().guess_head_span(span),
77 }),
78 );
79 }
80
81 match self.safety_context {
82 SafetyContext::UnsafeBlock {
83 nested_used_blocks: ref mut prev_nested_used_blocks,
84 ..
85 } => {
86 prev_nested_used_blocks.push(NestedUsedBlock { hir_id, span });
87 }
88 _ => (),
89 }
90 }
91 }
92 }
93
94 fn emit_deprecated_safe_fn_call(&self, span: Span, kind: &UnsafeOpKind) -> bool {
95 match kind {
96 &UnsafeOpKind::CallToUnsafeFunction(Some(id))
99 if !span.at_least_rust_2024()
100 && let Some(suggestion) = {
#[allow(deprecated)]
{
{
'done:
{
for i in self.tcx.get_all_attrs(id) {
#[allow(unused_imports)]
use rustc_hir::attrs::AttributeKind::*;
let i: &rustc_hir::Attribute = i;
match i {
rustc_hir::Attribute::Parsed(RustcDeprecatedSafe2024 {
suggestion }) => {
break 'done Some(suggestion);
}
rustc_hir::Attribute::Unparsed(..) =>
{}
#[deny(unreachable_patterns)]
_ => {}
}
}
None
}
}
}
}find_attr!(self.tcx, id, RustcDeprecatedSafe2024{suggestion} => suggestion) =>
101 {
102 let sm = self.tcx.sess.source_map();
103 let guarantee = ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("that {0}", suggestion))
})format!("that {}", suggestion);
104 let suggestion = sm
105 .indentation_before(span)
106 .map(|indent| ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0}// FIXME: Audit that {1}.\n",
indent, suggestion))
})format!("{}// FIXME: Audit that {}.\n", indent, suggestion))
107 .unwrap_or_default();
108
109 self.tcx.emit_node_span_lint(
110 DEPRECATED_SAFE_2024,
111 self.hir_context,
112 span,
113 CallToDeprecatedSafeFnRequiresUnsafe {
114 span,
115 function: { let _guard = NoTrimmedGuard::new(); self.tcx.def_path_str(id) }with_no_trimmed_paths!(self.tcx.def_path_str(id)),
116 sub: CallToDeprecatedSafeFnRequiresUnsafeSub {
117 start_of_line_suggestion: suggestion,
118 start_of_line: sm.span_extend_to_line(span).shrink_to_lo(),
119 left: span.shrink_to_lo(),
120 right: span.shrink_to_hi(),
121 guarantee,
122 },
123 },
124 );
125 true
126 }
127 _ => false,
128 }
129 }
130
131 fn requires_unsafe(&mut self, span: Span, kind: UnsafeOpKind) {
132 let unsafe_op_in_unsafe_fn_allowed = self.unsafe_op_in_unsafe_fn_allowed();
133 match self.safety_context {
134 SafetyContext::BuiltinUnsafeBlock => {}
135 SafetyContext::UnsafeBlock { ref mut used, .. } => {
136 *used = true;
141 }
142 SafetyContext::UnsafeFn if unsafe_op_in_unsafe_fn_allowed => {}
143 SafetyContext::UnsafeFn => {
144 let deprecated_safe_fn = self.emit_deprecated_safe_fn_call(span, &kind);
145 if !deprecated_safe_fn {
146 kind.emit_unsafe_op_in_unsafe_fn_lint(
148 self.tcx,
149 self.hir_context,
150 span,
151 self.suggest_unsafe_block,
152 );
153 self.suggest_unsafe_block = false;
154 }
155 }
156 SafetyContext::Safe => {
157 let deprecated_safe_fn = self.emit_deprecated_safe_fn_call(span, &kind);
158 if !deprecated_safe_fn {
159 kind.emit_requires_unsafe_err(
160 self.tcx,
161 span,
162 self.hir_context,
163 unsafe_op_in_unsafe_fn_allowed,
164 );
165 }
166 }
167 }
168 }
169
170 fn warn_unused_unsafe(
171 &mut self,
172 hir_id: HirId,
173 block_span: Span,
174 enclosing_unsafe: Option<UnusedUnsafeEnclosing>,
175 ) {
176 self.warnings.push(UnusedUnsafeWarning { hir_id, block_span, enclosing_unsafe });
177 }
178
179 fn unsafe_op_in_unsafe_fn_allowed(&self) -> bool {
181 self.tcx.lint_level_at_node(UNSAFE_OP_IN_UNSAFE_FN, self.hir_context).level == Level::Allow
182 }
183
184 fn visit_inner_body(&mut self, def: LocalDefId) {
186 if let Ok((inner_thir, expr)) = self.tcx.thir_body(def) {
187 self.tcx.ensure_done().mir_built(def);
189 let inner_thir = if self.tcx.sess.opts.unstable_opts.no_steal_thir {
190 &inner_thir.borrow()
191 } else {
192 &inner_thir.steal()
194 };
195 let hir_context = self.tcx.local_def_id_to_hir_id(def);
196 let safety_context = mem::replace(&mut self.safety_context, SafetyContext::Safe);
197 let mut inner_visitor = UnsafetyVisitor {
198 tcx: self.tcx,
199 thir: inner_thir,
200 hir_context,
201 safety_context,
202 body_target_features: self.body_target_features,
203 assignment_info: self.assignment_info,
204 in_union_destructure: false,
205 typing_env: self.typing_env,
206 inside_adt: false,
207 warnings: self.warnings,
208 suggest_unsafe_block: self.suggest_unsafe_block,
209 };
210 for param in &inner_thir.params {
212 if let Some(param_pat) = param.pat.as_deref() {
213 inner_visitor.visit_pat(param_pat);
214 }
215 }
216 inner_visitor.visit_expr(&inner_thir[expr]);
218 self.safety_context = inner_visitor.safety_context;
220 }
221 }
222}
223
224struct LayoutConstrainedPlaceVisitor<'a, 'tcx> {
226 found: bool,
227 thir: &'a Thir<'tcx>,
228 tcx: TyCtxt<'tcx>,
229}
230
231impl<'a, 'tcx> LayoutConstrainedPlaceVisitor<'a, 'tcx> {
232 fn new(thir: &'a Thir<'tcx>, tcx: TyCtxt<'tcx>) -> Self {
233 Self { found: false, thir, tcx }
234 }
235}
236
237impl<'a, 'tcx> Visitor<'a, 'tcx> for LayoutConstrainedPlaceVisitor<'a, 'tcx> {
238 fn thir(&self) -> &'a Thir<'tcx> {
239 self.thir
240 }
241
242 fn visit_expr(&mut self, expr: &'a Expr<'tcx>) {
243 match expr.kind {
244 ExprKind::Field { lhs, .. } => {
245 if let ty::Adt(adt_def, _) = self.thir[lhs].ty.kind() {
246 if (Bound::Unbounded, Bound::Unbounded)
247 != self.tcx.layout_scalar_valid_range(adt_def.did())
248 {
249 self.found = true;
250 }
251 }
252 visit::walk_expr(self, expr);
253 }
254
255 ExprKind::Deref { .. } => {}
259 ref kind if ExprCategory::of(kind).is_none_or(|cat| cat == ExprCategory::Place) => {
260 visit::walk_expr(self, expr);
261 }
262
263 _ => {}
264 }
265 }
266}
267
268impl<'a, 'tcx> Visitor<'a, 'tcx> for UnsafetyVisitor<'a, 'tcx> {
269 fn thir(&self) -> &'a Thir<'tcx> {
270 self.thir
271 }
272
273 fn visit_block(&mut self, block: &'a Block) {
274 match block.safety_mode {
275 BlockSafety::BuiltinUnsafe => {
278 self.in_safety_context(SafetyContext::BuiltinUnsafeBlock, |this| {
279 visit::walk_block(this, block)
280 });
281 }
282 BlockSafety::ExplicitUnsafe(hir_id) => {
283 let used = #[allow(non_exhaustive_omitted_patterns)] match self.tcx.lint_level_at_node(UNUSED_UNSAFE,
hir_id).level {
Level::Allow => true,
_ => false,
}matches!(
284 self.tcx.lint_level_at_node(UNUSED_UNSAFE, hir_id).level,
285 Level::Allow
286 );
287 self.in_safety_context(
288 SafetyContext::UnsafeBlock {
289 span: block.span,
290 hir_id,
291 used,
292 nested_used_blocks: Vec::new(),
293 },
294 |this| visit::walk_block(this, block),
295 );
296 }
297 BlockSafety::Safe => {
298 visit::walk_block(self, block);
299 }
300 }
301 }
302
303 fn visit_pat(&mut self, pat: &'a Pat<'tcx>) {
304 if self.in_union_destructure {
305 match pat.kind {
306 PatKind::Missing => ::core::panicking::panic("internal error: entered unreachable code")unreachable!(),
307 PatKind::Binding { .. }
309 | PatKind::Constant { .. }
311 | PatKind::Variant { .. }
312 | PatKind::Leaf { .. }
313 | PatKind::Deref { .. }
314 | PatKind::DerefPattern { .. }
315 | PatKind::Range { .. }
316 | PatKind::Slice { .. }
317 | PatKind::Array { .. }
318 | PatKind::Never => {
320 self.requires_unsafe(pat.span, AccessToUnionField);
321 return; }
323 PatKind::Wild |
325 PatKind::Or { .. } |
327 PatKind::Error(_) => {}
328 }
329 };
330
331 match &pat.kind {
332 PatKind::Leaf { subpatterns, .. } => {
333 if let ty::Adt(adt_def, ..) = pat.ty.kind() {
334 for pat in subpatterns {
335 if adt_def.non_enum_variant().fields[pat.field].safety.is_unsafe() {
336 self.requires_unsafe(pat.pattern.span, UseOfUnsafeField);
337 }
338 }
339 if adt_def.is_union() {
340 let old_in_union_destructure =
341 std::mem::replace(&mut self.in_union_destructure, true);
342 visit::walk_pat(self, pat);
343 self.in_union_destructure = old_in_union_destructure;
344 } else if (Bound::Unbounded, Bound::Unbounded)
345 != self.tcx.layout_scalar_valid_range(adt_def.did())
346 {
347 let old_inside_adt = std::mem::replace(&mut self.inside_adt, true);
348 visit::walk_pat(self, pat);
349 self.inside_adt = old_inside_adt;
350 } else {
351 visit::walk_pat(self, pat);
352 }
353 } else {
354 visit::walk_pat(self, pat);
355 }
356 }
357 PatKind::Variant { adt_def, args: _, variant_index, subpatterns } => {
358 for pat in subpatterns {
359 let field = &pat.field;
360 if adt_def.variant(*variant_index).fields[*field].safety.is_unsafe() {
361 self.requires_unsafe(pat.pattern.span, UseOfUnsafeField);
362 }
363 }
364 visit::walk_pat(self, pat);
365 }
366 PatKind::Binding { mode: BindingMode(ByRef::Yes(_, rm), _), ty, .. } => {
367 if self.inside_adt {
368 let ty::Ref(_, ty, _) = ty.kind() else {
369 ::rustc_middle::util::bug::span_bug_fmt(pat.span,
format_args!("ByRef::Yes in pattern, but found non-reference type {0}",
ty));span_bug!(
370 pat.span,
371 "ByRef::Yes in pattern, but found non-reference type {}",
372 ty
373 );
374 };
375 match rm {
376 Mutability::Not => {
377 if !ty.is_freeze(self.tcx, self.typing_env) {
378 self.requires_unsafe(pat.span, BorrowOfLayoutConstrainedField);
379 }
380 }
381 Mutability::Mut { .. } => {
382 self.requires_unsafe(pat.span, MutationOfLayoutConstrainedField);
383 }
384 }
385 }
386 visit::walk_pat(self, pat);
387 }
388 PatKind::Deref { .. } | PatKind::DerefPattern { .. } => {
389 let old_inside_adt = std::mem::replace(&mut self.inside_adt, false);
390 visit::walk_pat(self, pat);
391 self.inside_adt = old_inside_adt;
392 }
393 _ => {
394 visit::walk_pat(self, pat);
395 }
396 }
397 }
398
399 fn visit_expr(&mut self, expr: &'a Expr<'tcx>) {
400 match expr.kind {
402 ExprKind::Field { .. }
403 | ExprKind::VarRef { .. }
404 | ExprKind::UpvarRef { .. }
405 | ExprKind::Scope { .. }
406 | ExprKind::Cast { .. } => {}
407
408 ExprKind::RawBorrow { .. }
409 | ExprKind::Adt { .. }
410 | ExprKind::Array { .. }
411 | ExprKind::Binary { .. }
412 | ExprKind::Block { .. }
413 | ExprKind::Borrow { .. }
414 | ExprKind::Literal { .. }
415 | ExprKind::NamedConst { .. }
416 | ExprKind::NonHirLiteral { .. }
417 | ExprKind::ZstLiteral { .. }
418 | ExprKind::ConstParam { .. }
419 | ExprKind::ConstBlock { .. }
420 | ExprKind::Deref { .. }
421 | ExprKind::Index { .. }
422 | ExprKind::NeverToAny { .. }
423 | ExprKind::PlaceTypeAscription { .. }
424 | ExprKind::ValueTypeAscription { .. }
425 | ExprKind::PlaceUnwrapUnsafeBinder { .. }
426 | ExprKind::ValueUnwrapUnsafeBinder { .. }
427 | ExprKind::WrapUnsafeBinder { .. }
428 | ExprKind::PointerCoercion { .. }
429 | ExprKind::Repeat { .. }
430 | ExprKind::StaticRef { .. }
431 | ExprKind::ThreadLocalRef { .. }
432 | ExprKind::Tuple { .. }
433 | ExprKind::Unary { .. }
434 | ExprKind::Call { .. }
435 | ExprKind::ByUse { .. }
436 | ExprKind::Assign { .. }
437 | ExprKind::AssignOp { .. }
438 | ExprKind::Break { .. }
439 | ExprKind::Closure { .. }
440 | ExprKind::Continue { .. }
441 | ExprKind::ConstContinue { .. }
442 | ExprKind::Return { .. }
443 | ExprKind::Become { .. }
444 | ExprKind::Yield { .. }
445 | ExprKind::Loop { .. }
446 | ExprKind::LoopMatch { .. }
447 | ExprKind::Let { .. }
448 | ExprKind::Match { .. }
449 | ExprKind::If { .. }
450 | ExprKind::InlineAsm { .. }
451 | ExprKind::LogicalOp { .. }
452 | ExprKind::Use { .. } => {
453 self.assignment_info = None;
457 }
458 };
459 match expr.kind {
460 ExprKind::Scope { value, hir_id, region_scope: _ } => {
461 let prev_id = self.hir_context;
462 self.hir_context = hir_id;
463 ensure_sufficient_stack(|| {
464 self.visit_expr(&self.thir[value]);
465 });
466 self.hir_context = prev_id;
467 return; }
469 ExprKind::Call { fun, ty: _, args: _, from_hir_call: _, fn_span: _ } => {
470 let fn_ty = self.thir[fun].ty;
471 let sig = fn_ty.fn_sig(self.tcx);
472 let (callee_features, safe_target_features): (&[_], _) = match *fn_ty.kind() {
473 ty::FnDef(func_id, ..) => {
474 let cg_attrs = self.tcx.codegen_fn_attrs(func_id);
475 (&cg_attrs.target_features, cg_attrs.safe_target_features)
476 }
477 _ => (&[], false),
478 };
479 if sig.safety().is_unsafe() && !safe_target_features {
480 let func_id = if let ty::FnDef(func_id, _) = fn_ty.kind() {
481 Some(*func_id)
482 } else {
483 None
484 };
485 self.requires_unsafe(expr.span, CallToUnsafeFunction(func_id));
486 } else if let &ty::FnDef(func_did, _) = fn_ty.kind() {
487 if !self
488 .tcx
489 .is_target_feature_call_safe(callee_features, self.body_target_features)
490 {
491 let missing: Vec<_> = callee_features
492 .iter()
493 .copied()
494 .filter(|feature| {
495 feature.kind == TargetFeatureKind::Enabled
496 && !self
497 .body_target_features
498 .iter()
499 .any(|body_feature| body_feature.name == feature.name)
500 })
501 .map(|feature| feature.name)
502 .collect();
503 let build_enabled = self
504 .tcx
505 .sess
506 .target_features
507 .iter()
508 .copied()
509 .filter(|feature| missing.contains(feature))
510 .collect();
511 self.requires_unsafe(
512 expr.span,
513 CallToFunctionWith { function: func_did, missing, build_enabled },
514 );
515 }
516 }
517 }
518 ExprKind::RawBorrow { arg, .. } => {
519 if let ExprKind::Scope { value: arg, .. } = self.thir[arg].kind
520 && let ExprKind::Deref { arg } = self.thir[arg].kind
521 {
522 visit::walk_expr(self, &self.thir[arg]);
525 return;
526 }
527
528 let mut peeled = arg;
532 while let ExprKind::Scope { value: arg, .. } = self.thir[peeled].kind
533 && let ExprKind::Field { lhs, name: _, variant_index: _ } = self.thir[arg].kind
534 && let ty::Adt(def, _) = &self.thir[lhs].ty.kind()
535 && def.is_union()
536 {
537 peeled = lhs;
538 }
539 visit::walk_expr(self, &self.thir[peeled]);
540 return;
542 }
543 ExprKind::Deref { arg } => {
544 if let ExprKind::StaticRef { def_id, .. } | ExprKind::ThreadLocalRef(def_id) =
545 self.thir[arg].kind
546 {
547 if self.tcx.is_mutable_static(def_id) {
548 self.requires_unsafe(expr.span, UseOfMutableStatic);
549 } else if self.tcx.is_foreign_item(def_id) {
550 match self.tcx.def_kind(def_id) {
551 DefKind::Static { safety: hir::Safety::Safe, .. } => {}
552 _ => self.requires_unsafe(expr.span, UseOfExternStatic),
553 }
554 }
555 } else if self.thir[arg].ty.is_raw_ptr() {
556 self.requires_unsafe(expr.span, DerefOfRawPointer);
557 }
558 }
559 ExprKind::InlineAsm(box InlineAsmExpr {
560 asm_macro: asm_macro @ (AsmMacro::Asm | AsmMacro::NakedAsm),
561 ref operands,
562 template: _,
563 options: _,
564 line_spans: _,
565 }) => {
566 if let AsmMacro::Asm = asm_macro {
569 self.requires_unsafe(expr.span, UseOfInlineAssembly);
570 }
571
572 for op in &**operands {
575 use rustc_middle::thir::InlineAsmOperand::*;
576 match op {
577 In { expr, reg: _ }
578 | Out { expr: Some(expr), reg: _, late: _ }
579 | InOut { expr, reg: _, late: _ } => self.visit_expr(&self.thir()[*expr]),
580 SplitInOut { in_expr, out_expr, reg: _, late: _ } => {
581 self.visit_expr(&self.thir()[*in_expr]);
582 if let Some(out_expr) = out_expr {
583 self.visit_expr(&self.thir()[*out_expr]);
584 }
585 }
586 Out { expr: None, reg: _, late: _ }
587 | Const { value: _, span: _ }
588 | SymFn { value: _ }
589 | SymStatic { def_id: _ } => {}
590 Label { block } => {
591 self.in_safety_context(SafetyContext::Safe, |this| {
596 visit::walk_block(this, &this.thir()[*block])
597 });
598 }
599 }
600 }
601 return;
602 }
603 ExprKind::Adt(box AdtExpr {
604 adt_def,
605 variant_index,
606 args: _,
607 user_ty: _,
608 fields: _,
609 base: _,
610 }) => {
611 if adt_def.variant(variant_index).has_unsafe_fields() {
612 self.requires_unsafe(expr.span, InitializingTypeWithUnsafeField)
613 }
614 match self.tcx.layout_scalar_valid_range(adt_def.did()) {
615 (Bound::Unbounded, Bound::Unbounded) => {}
616 _ => self.requires_unsafe(expr.span, InitializingTypeWith),
617 }
618 }
619 ExprKind::Closure(box ClosureExpr {
620 closure_id,
621 args: _,
622 upvars: _,
623 movability: _,
624 fake_reads: _,
625 }) => {
626 self.visit_inner_body(closure_id);
627 }
628 ExprKind::ConstBlock { did, args: _ } => {
629 let def_id = did.expect_local();
630 self.visit_inner_body(def_id);
631 }
632 ExprKind::Field { lhs, variant_index, name } => {
633 let lhs = &self.thir[lhs];
634 if let ty::Adt(adt_def, _) = lhs.ty.kind() {
635 if adt_def.variant(variant_index).fields[name].safety.is_unsafe() {
636 self.requires_unsafe(expr.span, UseOfUnsafeField);
637 } else if adt_def.is_union() {
638 if let Some(assigned_ty) = self.assignment_info {
639 if assigned_ty.needs_drop(self.tcx, self.typing_env) {
640 if !self.tcx.dcx().has_errors().is_some() {
{
::core::panicking::panic_fmt(format_args!("union fields that need dropping should be impossible: {0}",
assigned_ty));
}
};assert!(
643 self.tcx.dcx().has_errors().is_some(),
644 "union fields that need dropping should be impossible: {assigned_ty}"
645 );
646 }
647 } else {
648 self.requires_unsafe(expr.span, AccessToUnionField);
649 }
650 }
651 }
652 }
653 ExprKind::Assign { lhs, rhs } | ExprKind::AssignOp { lhs, rhs, .. } => {
654 let lhs = &self.thir[lhs];
655 let mut visitor = LayoutConstrainedPlaceVisitor::new(self.thir, self.tcx);
657 visit::walk_expr(&mut visitor, lhs);
658 if visitor.found {
659 self.requires_unsafe(expr.span, MutationOfLayoutConstrainedField);
660 }
661
662 if #[allow(non_exhaustive_omitted_patterns)] match expr.kind {
ExprKind::Assign { .. } => true,
_ => false,
}matches!(expr.kind, ExprKind::Assign { .. }) {
666 self.assignment_info = Some(lhs.ty);
667 visit::walk_expr(self, lhs);
668 self.assignment_info = None;
669 visit::walk_expr(self, &self.thir()[rhs]);
670 return; }
672 }
673 ExprKind::Borrow { borrow_kind, arg } => {
674 let mut visitor = LayoutConstrainedPlaceVisitor::new(self.thir, self.tcx);
675 visit::walk_expr(&mut visitor, expr);
676 if visitor.found {
677 match borrow_kind {
678 BorrowKind::Fake(_) | BorrowKind::Shared
679 if !self.thir[arg].ty.is_freeze(self.tcx, self.typing_env) =>
680 {
681 self.requires_unsafe(expr.span, BorrowOfLayoutConstrainedField)
682 }
683 BorrowKind::Mut { .. } => {
684 self.requires_unsafe(expr.span, MutationOfLayoutConstrainedField)
685 }
686 BorrowKind::Fake(_) | BorrowKind::Shared => {}
687 }
688 }
689 }
690 ExprKind::PlaceUnwrapUnsafeBinder { .. }
691 | ExprKind::ValueUnwrapUnsafeBinder { .. }
692 | ExprKind::WrapUnsafeBinder { .. } => {
693 self.requires_unsafe(expr.span, UnsafeBinderCast);
694 }
695 _ => {}
696 }
697 visit::walk_expr(self, expr);
698 }
699}
700
701#[derive(#[automatically_derived]
impl ::core::clone::Clone for SafetyContext {
#[inline]
fn clone(&self) -> SafetyContext {
match self {
SafetyContext::Safe => SafetyContext::Safe,
SafetyContext::BuiltinUnsafeBlock =>
SafetyContext::BuiltinUnsafeBlock,
SafetyContext::UnsafeFn => SafetyContext::UnsafeFn,
SafetyContext::UnsafeBlock {
span: __self_0,
hir_id: __self_1,
used: __self_2,
nested_used_blocks: __self_3 } =>
SafetyContext::UnsafeBlock {
span: ::core::clone::Clone::clone(__self_0),
hir_id: ::core::clone::Clone::clone(__self_1),
used: ::core::clone::Clone::clone(__self_2),
nested_used_blocks: ::core::clone::Clone::clone(__self_3),
},
}
}
}Clone)]
702enum SafetyContext {
703 Safe,
704 BuiltinUnsafeBlock,
705 UnsafeFn,
706 UnsafeBlock { span: Span, hir_id: HirId, used: bool, nested_used_blocks: Vec<NestedUsedBlock> },
707}
708
709#[derive(#[automatically_derived]
impl ::core::clone::Clone for NestedUsedBlock {
#[inline]
fn clone(&self) -> NestedUsedBlock {
let _: ::core::clone::AssertParamIsClone<HirId>;
let _: ::core::clone::AssertParamIsClone<Span>;
*self
}
}Clone, #[automatically_derived]
impl ::core::marker::Copy for NestedUsedBlock { }Copy)]
710struct NestedUsedBlock {
711 hir_id: HirId,
712 span: Span,
713}
714
715struct UnusedUnsafeWarning {
716 hir_id: HirId,
717 block_span: Span,
718 enclosing_unsafe: Option<UnusedUnsafeEnclosing>,
719}
720
721#[derive(#[automatically_derived]
impl ::core::clone::Clone for UnsafeOpKind {
#[inline]
fn clone(&self) -> UnsafeOpKind {
match self {
UnsafeOpKind::CallToUnsafeFunction(__self_0) =>
UnsafeOpKind::CallToUnsafeFunction(::core::clone::Clone::clone(__self_0)),
UnsafeOpKind::UseOfInlineAssembly =>
UnsafeOpKind::UseOfInlineAssembly,
UnsafeOpKind::InitializingTypeWith =>
UnsafeOpKind::InitializingTypeWith,
UnsafeOpKind::InitializingTypeWithUnsafeField =>
UnsafeOpKind::InitializingTypeWithUnsafeField,
UnsafeOpKind::UseOfMutableStatic =>
UnsafeOpKind::UseOfMutableStatic,
UnsafeOpKind::UseOfExternStatic =>
UnsafeOpKind::UseOfExternStatic,
UnsafeOpKind::UseOfUnsafeField => UnsafeOpKind::UseOfUnsafeField,
UnsafeOpKind::DerefOfRawPointer =>
UnsafeOpKind::DerefOfRawPointer,
UnsafeOpKind::AccessToUnionField =>
UnsafeOpKind::AccessToUnionField,
UnsafeOpKind::MutationOfLayoutConstrainedField =>
UnsafeOpKind::MutationOfLayoutConstrainedField,
UnsafeOpKind::BorrowOfLayoutConstrainedField =>
UnsafeOpKind::BorrowOfLayoutConstrainedField,
UnsafeOpKind::CallToFunctionWith {
function: __self_0, missing: __self_1, build_enabled: __self_2
} =>
UnsafeOpKind::CallToFunctionWith {
function: ::core::clone::Clone::clone(__self_0),
missing: ::core::clone::Clone::clone(__self_1),
build_enabled: ::core::clone::Clone::clone(__self_2),
},
UnsafeOpKind::UnsafeBinderCast => UnsafeOpKind::UnsafeBinderCast,
}
}
}Clone, #[automatically_derived]
impl ::core::cmp::PartialEq for UnsafeOpKind {
#[inline]
fn eq(&self, other: &UnsafeOpKind) -> bool {
let __self_discr = ::core::intrinsics::discriminant_value(self);
let __arg1_discr = ::core::intrinsics::discriminant_value(other);
__self_discr == __arg1_discr &&
match (self, other) {
(UnsafeOpKind::CallToUnsafeFunction(__self_0),
UnsafeOpKind::CallToUnsafeFunction(__arg1_0)) =>
__self_0 == __arg1_0,
(UnsafeOpKind::CallToFunctionWith {
function: __self_0,
missing: __self_1,
build_enabled: __self_2 },
UnsafeOpKind::CallToFunctionWith {
function: __arg1_0,
missing: __arg1_1,
build_enabled: __arg1_2 }) =>
__self_0 == __arg1_0 && __self_1 == __arg1_1 &&
__self_2 == __arg1_2,
_ => true,
}
}
}PartialEq)]
722enum UnsafeOpKind {
723 CallToUnsafeFunction(Option<DefId>),
724 UseOfInlineAssembly,
725 InitializingTypeWith,
726 InitializingTypeWithUnsafeField,
727 UseOfMutableStatic,
728 UseOfExternStatic,
729 UseOfUnsafeField,
730 DerefOfRawPointer,
731 AccessToUnionField,
732 MutationOfLayoutConstrainedField,
733 BorrowOfLayoutConstrainedField,
734 CallToFunctionWith {
735 function: DefId,
736 missing: Vec<Symbol>,
739 build_enabled: Vec<Symbol>,
742 },
743 UnsafeBinderCast,
744}
745
746use UnsafeOpKind::*;
747
748impl UnsafeOpKind {
749 fn emit_unsafe_op_in_unsafe_fn_lint(
750 &self,
751 tcx: TyCtxt<'_>,
752 hir_id: HirId,
753 span: Span,
754 suggest_unsafe_block: bool,
755 ) {
756 if tcx.hir_opt_delegation_sig_id(hir_id.owner.def_id).is_some() {
757 return;
760 }
761 let parent_id = tcx.hir_get_parent_item(hir_id);
762 let parent_owner = tcx.hir_owner_node(parent_id);
763 let should_suggest = parent_owner.fn_sig().is_some_and(|sig| {
764 #[allow(non_exhaustive_omitted_patterns)] match sig.header.safety {
hir::HeaderSafety::Normal(hir::Safety::Unsafe) => true,
_ => false,
}matches!(sig.header.safety, hir::HeaderSafety::Normal(hir::Safety::Unsafe))
766 });
767 let unsafe_not_inherited_note = if should_suggest {
768 suggest_unsafe_block.then(|| {
769 let body_span = tcx.hir_body(parent_owner.body_id().unwrap()).value.span;
770 UnsafeNotInheritedLintNote {
771 signature_span: tcx.def_span(parent_id.def_id),
772 body_span,
773 }
774 })
775 } else {
776 None
777 };
778 match self {
781 CallToUnsafeFunction(Some(did)) => tcx.emit_node_span_lint(
782 UNSAFE_OP_IN_UNSAFE_FN,
783 hir_id,
784 span,
785 UnsafeOpInUnsafeFnCallToUnsafeFunctionRequiresUnsafe {
786 span,
787 function: { let _guard = NoTrimmedGuard::new(); tcx.def_path_str(*did) }with_no_trimmed_paths!(tcx.def_path_str(*did)),
788 unsafe_not_inherited_note,
789 },
790 ),
791 CallToUnsafeFunction(None) => tcx.emit_node_span_lint(
792 UNSAFE_OP_IN_UNSAFE_FN,
793 hir_id,
794 span,
795 UnsafeOpInUnsafeFnCallToUnsafeFunctionRequiresUnsafeNameless {
796 span,
797 unsafe_not_inherited_note,
798 },
799 ),
800 UseOfInlineAssembly => tcx.emit_node_span_lint(
801 UNSAFE_OP_IN_UNSAFE_FN,
802 hir_id,
803 span,
804 UnsafeOpInUnsafeFnUseOfInlineAssemblyRequiresUnsafe {
805 span,
806 unsafe_not_inherited_note,
807 },
808 ),
809 InitializingTypeWith => tcx.emit_node_span_lint(
810 UNSAFE_OP_IN_UNSAFE_FN,
811 hir_id,
812 span,
813 UnsafeOpInUnsafeFnInitializingTypeWithRequiresUnsafe {
814 span,
815 unsafe_not_inherited_note,
816 },
817 ),
818 InitializingTypeWithUnsafeField => tcx.emit_node_span_lint(
819 UNSAFE_OP_IN_UNSAFE_FN,
820 hir_id,
821 span,
822 UnsafeOpInUnsafeFnInitializingTypeWithUnsafeFieldRequiresUnsafe {
823 span,
824 unsafe_not_inherited_note,
825 },
826 ),
827 UseOfMutableStatic => tcx.emit_node_span_lint(
828 UNSAFE_OP_IN_UNSAFE_FN,
829 hir_id,
830 span,
831 UnsafeOpInUnsafeFnUseOfMutableStaticRequiresUnsafe {
832 span,
833 unsafe_not_inherited_note,
834 },
835 ),
836 UseOfExternStatic => tcx.emit_node_span_lint(
837 UNSAFE_OP_IN_UNSAFE_FN,
838 hir_id,
839 span,
840 UnsafeOpInUnsafeFnUseOfExternStaticRequiresUnsafe {
841 span,
842 unsafe_not_inherited_note,
843 },
844 ),
845 UseOfUnsafeField => tcx.emit_node_span_lint(
846 UNSAFE_OP_IN_UNSAFE_FN,
847 hir_id,
848 span,
849 UnsafeOpInUnsafeFnUseOfUnsafeFieldRequiresUnsafe {
850 span,
851 unsafe_not_inherited_note,
852 },
853 ),
854 DerefOfRawPointer => tcx.emit_node_span_lint(
855 UNSAFE_OP_IN_UNSAFE_FN,
856 hir_id,
857 span,
858 UnsafeOpInUnsafeFnDerefOfRawPointerRequiresUnsafe {
859 span,
860 unsafe_not_inherited_note,
861 },
862 ),
863 AccessToUnionField => tcx.emit_node_span_lint(
864 UNSAFE_OP_IN_UNSAFE_FN,
865 hir_id,
866 span,
867 UnsafeOpInUnsafeFnAccessToUnionFieldRequiresUnsafe {
868 span,
869 unsafe_not_inherited_note,
870 },
871 ),
872 MutationOfLayoutConstrainedField => tcx.emit_node_span_lint(
873 UNSAFE_OP_IN_UNSAFE_FN,
874 hir_id,
875 span,
876 UnsafeOpInUnsafeFnMutationOfLayoutConstrainedFieldRequiresUnsafe {
877 span,
878 unsafe_not_inherited_note,
879 },
880 ),
881 BorrowOfLayoutConstrainedField => tcx.emit_node_span_lint(
882 UNSAFE_OP_IN_UNSAFE_FN,
883 hir_id,
884 span,
885 UnsafeOpInUnsafeFnBorrowOfLayoutConstrainedFieldRequiresUnsafe {
886 span,
887 unsafe_not_inherited_note,
888 },
889 ),
890 CallToFunctionWith { function, missing, build_enabled } => tcx.emit_node_span_lint(
891 UNSAFE_OP_IN_UNSAFE_FN,
892 hir_id,
893 span,
894 UnsafeOpInUnsafeFnCallToFunctionWithRequiresUnsafe {
895 span,
896 function: { let _guard = NoTrimmedGuard::new(); tcx.def_path_str(*function) }with_no_trimmed_paths!(tcx.def_path_str(*function)),
897 missing_target_features: DiagArgValue::StrListSepByAnd(
898 missing.iter().map(|feature| Cow::from(feature.to_string())).collect(),
899 ),
900 missing_target_features_count: missing.len(),
901 note: !build_enabled.is_empty(),
902 build_target_features: DiagArgValue::StrListSepByAnd(
903 build_enabled
904 .iter()
905 .map(|feature| Cow::from(feature.to_string()))
906 .collect(),
907 ),
908 build_target_features_count: build_enabled.len(),
909 unsafe_not_inherited_note,
910 },
911 ),
912 UnsafeBinderCast => tcx.emit_node_span_lint(
913 UNSAFE_OP_IN_UNSAFE_FN,
914 hir_id,
915 span,
916 UnsafeOpInUnsafeFnUnsafeBinderCastRequiresUnsafe {
917 span,
918 unsafe_not_inherited_note,
919 },
920 ),
921 }
922 }
923
924 fn emit_requires_unsafe_err(
925 &self,
926 tcx: TyCtxt<'_>,
927 span: Span,
928 hir_context: HirId,
929 unsafe_op_in_unsafe_fn_allowed: bool,
930 ) {
931 let note_non_inherited = tcx.hir_parent_iter(hir_context).find(|(id, node)| {
932 if let hir::Node::Expr(block) = node
933 && let hir::ExprKind::Block(block, _) = block.kind
934 && let hir::BlockCheckMode::UnsafeBlock(_) = block.rules
935 {
936 true
937 } else if let Some(sig) = tcx.hir_fn_sig_by_hir_id(*id)
938 && #[allow(non_exhaustive_omitted_patterns)] match sig.header.safety {
hir::HeaderSafety::Normal(hir::Safety::Unsafe) => true,
_ => false,
}matches!(sig.header.safety, hir::HeaderSafety::Normal(hir::Safety::Unsafe))
939 {
940 true
941 } else {
942 false
943 }
944 });
945 let unsafe_not_inherited_note = if let Some((id, _)) = note_non_inherited {
946 let span = tcx.hir_span(id);
947 let span = tcx.sess.source_map().guess_head_span(span);
948 Some(UnsafeNotInheritedNote { span })
949 } else {
950 None
951 };
952
953 let dcx = tcx.dcx();
954 match self {
955 CallToUnsafeFunction(Some(did)) if unsafe_op_in_unsafe_fn_allowed => {
956 dcx.emit_err(CallToUnsafeFunctionRequiresUnsafeUnsafeOpInUnsafeFnAllowed {
957 span,
958 unsafe_not_inherited_note,
959 function: tcx.def_path_str(*did),
960 });
961 }
962 CallToUnsafeFunction(Some(did)) => {
963 dcx.emit_err(CallToUnsafeFunctionRequiresUnsafe {
964 span,
965 unsafe_not_inherited_note,
966 function: tcx.def_path_str(*did),
967 });
968 }
969 CallToUnsafeFunction(None) if unsafe_op_in_unsafe_fn_allowed => {
970 dcx.emit_err(CallToUnsafeFunctionRequiresUnsafeNamelessUnsafeOpInUnsafeFnAllowed {
971 span,
972 unsafe_not_inherited_note,
973 });
974 }
975 CallToUnsafeFunction(None) => {
976 dcx.emit_err(CallToUnsafeFunctionRequiresUnsafeNameless {
977 span,
978 unsafe_not_inherited_note,
979 });
980 }
981 UseOfInlineAssembly if unsafe_op_in_unsafe_fn_allowed => {
982 dcx.emit_err(UseOfInlineAssemblyRequiresUnsafeUnsafeOpInUnsafeFnAllowed {
983 span,
984 unsafe_not_inherited_note,
985 });
986 }
987 UseOfInlineAssembly => {
988 dcx.emit_err(UseOfInlineAssemblyRequiresUnsafe { span, unsafe_not_inherited_note });
989 }
990 InitializingTypeWith if unsafe_op_in_unsafe_fn_allowed => {
991 dcx.emit_err(InitializingTypeWithRequiresUnsafeUnsafeOpInUnsafeFnAllowed {
992 span,
993 unsafe_not_inherited_note,
994 });
995 }
996 InitializingTypeWith => {
997 dcx.emit_err(InitializingTypeWithRequiresUnsafe {
998 span,
999 unsafe_not_inherited_note,
1000 });
1001 }
1002 InitializingTypeWithUnsafeField if unsafe_op_in_unsafe_fn_allowed => {
1003 dcx.emit_err(
1004 InitializingTypeWithUnsafeFieldRequiresUnsafeUnsafeOpInUnsafeFnAllowed {
1005 span,
1006 unsafe_not_inherited_note,
1007 },
1008 );
1009 }
1010 InitializingTypeWithUnsafeField => {
1011 dcx.emit_err(InitializingTypeWithUnsafeFieldRequiresUnsafe {
1012 span,
1013 unsafe_not_inherited_note,
1014 });
1015 }
1016 UseOfMutableStatic if unsafe_op_in_unsafe_fn_allowed => {
1017 dcx.emit_err(UseOfMutableStaticRequiresUnsafeUnsafeOpInUnsafeFnAllowed {
1018 span,
1019 unsafe_not_inherited_note,
1020 });
1021 }
1022 UseOfMutableStatic => {
1023 dcx.emit_err(UseOfMutableStaticRequiresUnsafe { span, unsafe_not_inherited_note });
1024 }
1025 UseOfExternStatic if unsafe_op_in_unsafe_fn_allowed => {
1026 dcx.emit_err(UseOfExternStaticRequiresUnsafeUnsafeOpInUnsafeFnAllowed {
1027 span,
1028 unsafe_not_inherited_note,
1029 });
1030 }
1031 UseOfExternStatic => {
1032 dcx.emit_err(UseOfExternStaticRequiresUnsafe { span, unsafe_not_inherited_note });
1033 }
1034 UseOfUnsafeField if unsafe_op_in_unsafe_fn_allowed => {
1035 dcx.emit_err(UseOfUnsafeFieldRequiresUnsafeUnsafeOpInUnsafeFnAllowed {
1036 span,
1037 unsafe_not_inherited_note,
1038 });
1039 }
1040 UseOfUnsafeField => {
1041 dcx.emit_err(UseOfUnsafeFieldRequiresUnsafe { span, unsafe_not_inherited_note });
1042 }
1043 DerefOfRawPointer if unsafe_op_in_unsafe_fn_allowed => {
1044 dcx.emit_err(DerefOfRawPointerRequiresUnsafeUnsafeOpInUnsafeFnAllowed {
1045 span,
1046 unsafe_not_inherited_note,
1047 });
1048 }
1049 DerefOfRawPointer => {
1050 dcx.emit_err(DerefOfRawPointerRequiresUnsafe { span, unsafe_not_inherited_note });
1051 }
1052 AccessToUnionField if unsafe_op_in_unsafe_fn_allowed => {
1053 dcx.emit_err(AccessToUnionFieldRequiresUnsafeUnsafeOpInUnsafeFnAllowed {
1054 span,
1055 unsafe_not_inherited_note,
1056 });
1057 }
1058 AccessToUnionField => {
1059 dcx.emit_err(AccessToUnionFieldRequiresUnsafe { span, unsafe_not_inherited_note });
1060 }
1061 MutationOfLayoutConstrainedField if unsafe_op_in_unsafe_fn_allowed => {
1062 dcx.emit_err(
1063 MutationOfLayoutConstrainedFieldRequiresUnsafeUnsafeOpInUnsafeFnAllowed {
1064 span,
1065 unsafe_not_inherited_note,
1066 },
1067 );
1068 }
1069 MutationOfLayoutConstrainedField => {
1070 dcx.emit_err(MutationOfLayoutConstrainedFieldRequiresUnsafe {
1071 span,
1072 unsafe_not_inherited_note,
1073 });
1074 }
1075 BorrowOfLayoutConstrainedField if unsafe_op_in_unsafe_fn_allowed => {
1076 dcx.emit_err(
1077 BorrowOfLayoutConstrainedFieldRequiresUnsafeUnsafeOpInUnsafeFnAllowed {
1078 span,
1079 unsafe_not_inherited_note,
1080 },
1081 );
1082 }
1083 BorrowOfLayoutConstrainedField => {
1084 dcx.emit_err(BorrowOfLayoutConstrainedFieldRequiresUnsafe {
1085 span,
1086 unsafe_not_inherited_note,
1087 });
1088 }
1089 CallToFunctionWith { function, missing, build_enabled }
1090 if unsafe_op_in_unsafe_fn_allowed =>
1091 {
1092 dcx.emit_err(CallToFunctionWithRequiresUnsafeUnsafeOpInUnsafeFnAllowed {
1093 span,
1094 missing_target_features: DiagArgValue::StrListSepByAnd(
1095 missing.iter().map(|feature| Cow::from(feature.to_string())).collect(),
1096 ),
1097 missing_target_features_count: missing.len(),
1098 note: !build_enabled.is_empty(),
1099 build_target_features: DiagArgValue::StrListSepByAnd(
1100 build_enabled
1101 .iter()
1102 .map(|feature| Cow::from(feature.to_string()))
1103 .collect(),
1104 ),
1105 build_target_features_count: build_enabled.len(),
1106 unsafe_not_inherited_note,
1107 function: tcx.def_path_str(*function),
1108 });
1109 }
1110 CallToFunctionWith { function, missing, build_enabled } => {
1111 dcx.emit_err(CallToFunctionWithRequiresUnsafe {
1112 span,
1113 missing_target_features: DiagArgValue::StrListSepByAnd(
1114 missing.iter().map(|feature| Cow::from(feature.to_string())).collect(),
1115 ),
1116 missing_target_features_count: missing.len(),
1117 note: !build_enabled.is_empty(),
1118 build_target_features: DiagArgValue::StrListSepByAnd(
1119 build_enabled
1120 .iter()
1121 .map(|feature| Cow::from(feature.to_string()))
1122 .collect(),
1123 ),
1124 build_target_features_count: build_enabled.len(),
1125 unsafe_not_inherited_note,
1126 function: tcx.def_path_str(*function),
1127 });
1128 }
1129 UnsafeBinderCast if unsafe_op_in_unsafe_fn_allowed => {
1130 dcx.emit_err(UnsafeBinderCastRequiresUnsafeUnsafeOpInUnsafeFnAllowed {
1131 span,
1132 unsafe_not_inherited_note,
1133 });
1134 }
1135 UnsafeBinderCast => {
1136 dcx.emit_err(UnsafeBinderCastRequiresUnsafe { span, unsafe_not_inherited_note });
1137 }
1138 }
1139 }
1140}
1141
1142pub(crate) fn check_unsafety(tcx: TyCtxt<'_>, def: LocalDefId) {
1143 if !!tcx.is_typeck_child(def.to_def_id()) {
::core::panicking::panic("assertion failed: !tcx.is_typeck_child(def.to_def_id())")
};assert!(!tcx.is_typeck_child(def.to_def_id()));
1145 if {
#[allow(deprecated)]
{
{
'done:
{
for i in tcx.get_all_attrs(def) {
#[allow(unused_imports)]
use rustc_hir::attrs::AttributeKind::*;
let i: &rustc_hir::Attribute = i;
match i {
rustc_hir::Attribute::Parsed(CustomMir(..)) => {
break 'done Some(());
}
rustc_hir::Attribute::Unparsed(..) =>
{}
#[deny(unreachable_patterns)]
_ => {}
}
}
None
}
}
}
}find_attr!(tcx, def, CustomMir(..) => ()).is_some() {
1147 return;
1148 }
1149
1150 let Ok((thir, expr)) = tcx.thir_body(def) else { return };
1151 tcx.ensure_done().mir_built(def);
1153 let thir = if tcx.sess.opts.unstable_opts.no_steal_thir {
1154 &thir.borrow()
1155 } else {
1156 &thir.steal()
1158 };
1159
1160 let hir_id = tcx.local_def_id_to_hir_id(def);
1161 let safety_context = tcx.hir_fn_sig_by_hir_id(hir_id).map_or(SafetyContext::Safe, |fn_sig| {
1162 match fn_sig.header.safety {
1163 hir::HeaderSafety::SafeTargetFeatures => SafetyContext::Safe,
1167 hir::HeaderSafety::Normal(safety) => match safety {
1168 hir::Safety::Unsafe => SafetyContext::UnsafeFn,
1169 hir::Safety::Safe => SafetyContext::Safe,
1170 },
1171 }
1172 });
1173 let body_target_features = &tcx.body_codegen_attrs(def.to_def_id()).target_features;
1174 let mut warnings = Vec::new();
1175 let mut visitor = UnsafetyVisitor {
1176 tcx,
1177 thir,
1178 safety_context,
1179 hir_context: hir_id,
1180 body_target_features,
1181 assignment_info: None,
1182 in_union_destructure: false,
1183 typing_env: ty::TypingEnv::non_body_analysis(tcx, def),
1185 inside_adt: false,
1186 warnings: &mut warnings,
1187 suggest_unsafe_block: true,
1188 };
1189 for param in &thir.params {
1191 if let Some(param_pat) = param.pat.as_deref() {
1192 visitor.visit_pat(param_pat);
1193 }
1194 }
1195 visitor.visit_expr(&thir[expr]);
1197
1198 warnings.sort_by_key(|w| w.block_span);
1199 for UnusedUnsafeWarning { hir_id, block_span, enclosing_unsafe } in warnings {
1200 let block_span = tcx.sess.source_map().guess_head_span(block_span);
1201 tcx.emit_node_span_lint(
1202 UNUSED_UNSAFE,
1203 hir_id,
1204 block_span,
1205 UnusedUnsafe { span: block_span, enclosing: enclosing_unsafe },
1206 );
1207 }
1208}