Skip to content

Commit 61a3eea

Browse files
committed
Auto merge of #117229 - matthewjasper:thir-unsafeck-fixes, r=cjgillot
Thir unsafeck fixes - Recognise thread local statics in THIR unsafeck - Add suggestion for unsafe_op_in_unsafe_fn - Fix unsafe checking of let expressions
2 parents 114f1f6 + 868de8e commit 61a3eea

24 files changed

+489
-85
lines changed

compiler/rustc_hir/src/hir.rs

+9
Original file line numberDiff line numberDiff line change
@@ -3566,6 +3566,15 @@ impl<'hir> OwnerNode<'hir> {
35663566
}
35673567
}
35683568

3569+
pub fn fn_sig(self) -> Option<&'hir FnSig<'hir>> {
3570+
match self {
3571+
OwnerNode::TraitItem(TraitItem { kind: TraitItemKind::Fn(fn_sig, _), .. })
3572+
| OwnerNode::ImplItem(ImplItem { kind: ImplItemKind::Fn(fn_sig, _), .. })
3573+
| OwnerNode::Item(Item { kind: ItemKind::Fn(fn_sig, _, _), .. }) => Some(fn_sig),
3574+
_ => None,
3575+
}
3576+
}
3577+
35693578
pub fn fn_decl(self) -> Option<&'hir FnDecl<'hir>> {
35703579
match self {
35713580
OwnerNode::TraitItem(TraitItem { kind: TraitItemKind::Fn(fn_sig, _), .. })

compiler/rustc_middle/src/thir/visit.rs

+2-1
Original file line numberDiff line numberDiff line change
@@ -66,8 +66,9 @@ pub fn walk_expr<'a, 'tcx: 'a, V: Visitor<'a, 'tcx>>(visitor: &mut V, expr: &Exp
6666
Use { source } => visitor.visit_expr(&visitor.thir()[source]),
6767
NeverToAny { source } => visitor.visit_expr(&visitor.thir()[source]),
6868
PointerCoercion { source, cast: _ } => visitor.visit_expr(&visitor.thir()[source]),
69-
Let { expr, .. } => {
69+
Let { expr, ref pat } => {
7070
visitor.visit_expr(&visitor.thir()[expr]);
71+
visitor.visit_pat(pat);
7172
}
7273
Loop { body } => visitor.visit_expr(&visitor.thir()[body]),
7374
Match { scrutinee, ref arms, .. } => {

compiler/rustc_mir_build/messages.ftl

+3
Original file line numberDiff line numberDiff line change
@@ -320,6 +320,7 @@ mir_build_unreachable_pattern = unreachable pattern
320320
.label = unreachable pattern
321321
.catchall_label = matches any value
322322
323+
mir_build_unsafe_fn_safe_body = an unsafe function restricts its caller, but its body is safe by default
323324
mir_build_unsafe_not_inherited = items do not inherit unsafety from separate enclosing items
324325
325326
mir_build_unsafe_op_in_unsafe_fn_borrow_of_layout_constrained_field_requires_unsafe =
@@ -386,3 +387,5 @@ mir_build_unused_unsafe = unnecessary `unsafe` block
386387
mir_build_unused_unsafe_enclosing_block_label = because it's nested under this `unsafe` block
387388
388389
mir_build_variant_defined_here = not covered
390+
391+
mir_build_wrap_suggestion = consider wrapping the function body in an unsafe block

compiler/rustc_mir_build/src/check_unsafety.rs

+69-19
Original file line numberDiff line numberDiff line change
@@ -35,6 +35,10 @@ struct UnsafetyVisitor<'a, 'tcx> {
3535
param_env: ParamEnv<'tcx>,
3636
inside_adt: bool,
3737
warnings: &'a mut Vec<UnusedUnsafeWarning>,
38+
39+
/// Flag to ensure that we only suggest wrapping the entire function body in
40+
/// an unsafe block once.
41+
suggest_unsafe_block: bool,
3842
}
3943

4044
impl<'tcx> UnsafetyVisitor<'_, 'tcx> {
@@ -95,7 +99,13 @@ impl<'tcx> UnsafetyVisitor<'_, 'tcx> {
9599
SafetyContext::UnsafeFn if unsafe_op_in_unsafe_fn_allowed => {}
96100
SafetyContext::UnsafeFn => {
97101
// unsafe_op_in_unsafe_fn is disallowed
98-
kind.emit_unsafe_op_in_unsafe_fn_lint(self.tcx, self.hir_context, span);
102+
kind.emit_unsafe_op_in_unsafe_fn_lint(
103+
self.tcx,
104+
self.hir_context,
105+
span,
106+
self.suggest_unsafe_block,
107+
);
108+
self.suggest_unsafe_block = false;
99109
}
100110
SafetyContext::Safe => {
101111
kind.emit_requires_unsafe_err(
@@ -297,6 +307,7 @@ impl<'a, 'tcx> Visitor<'a, 'tcx> for UnsafetyVisitor<'a, 'tcx> {
297307
}
298308
PatKind::InlineConstant { def, .. } => {
299309
self.visit_inner_body(*def);
310+
visit::walk_pat(self, pat);
300311
}
301312
_ => {
302313
visit::walk_pat(self, pat);
@@ -394,7 +405,9 @@ impl<'a, 'tcx> Visitor<'a, 'tcx> for UnsafetyVisitor<'a, 'tcx> {
394405
}
395406
}
396407
ExprKind::Deref { arg } => {
397-
if let ExprKind::StaticRef { def_id, .. } = self.thir[arg].kind {
408+
if let ExprKind::StaticRef { def_id, .. } | ExprKind::ThreadLocalRef(def_id) =
409+
self.thir[arg].kind
410+
{
398411
if self.tcx.is_mutable_static(def_id) {
399412
self.requires_unsafe(expr.span, UseOfMutableStatic);
400413
} else if self.tcx.is_foreign_item(def_id) {
@@ -482,14 +495,6 @@ impl<'a, 'tcx> Visitor<'a, 'tcx> for UnsafetyVisitor<'a, 'tcx> {
482495
}
483496
}
484497
}
485-
ExprKind::Let { expr: expr_id, .. } => {
486-
let let_expr = &self.thir[expr_id];
487-
if let ty::Adt(adt_def, _) = let_expr.ty.kind()
488-
&& adt_def.is_union()
489-
{
490-
self.requires_unsafe(expr.span, AccessToUnionField);
491-
}
492-
}
493498
_ => {}
494499
}
495500
visit::walk_expr(self, expr);
@@ -543,7 +548,22 @@ impl UnsafeOpKind {
543548
tcx: TyCtxt<'_>,
544549
hir_id: hir::HirId,
545550
span: Span,
551+
suggest_unsafe_block: bool,
546552
) {
553+
let parent_id = tcx.hir().get_parent_item(hir_id);
554+
let parent_owner = tcx.hir().owner(parent_id);
555+
let should_suggest = parent_owner.fn_sig().map_or(false, |sig| sig.header.is_unsafe());
556+
let unsafe_not_inherited_note = if should_suggest {
557+
suggest_unsafe_block.then(|| {
558+
let body_span = tcx.hir().body(parent_owner.body_id().unwrap()).value.span;
559+
UnsafeNotInheritedLintNote {
560+
signature_span: tcx.def_span(parent_id.def_id),
561+
body_span,
562+
}
563+
})
564+
} else {
565+
None
566+
};
547567
// FIXME: ideally we would want to trim the def paths, but this is not
548568
// feasible with the current lint emission API (see issue #106126).
549569
match self {
@@ -554,61 +574,89 @@ impl UnsafeOpKind {
554574
UnsafeOpInUnsafeFnCallToUnsafeFunctionRequiresUnsafe {
555575
span,
556576
function: &with_no_trimmed_paths!(tcx.def_path_str(*did)),
577+
unsafe_not_inherited_note,
557578
},
558579
),
559580
CallToUnsafeFunction(None) => tcx.emit_spanned_lint(
560581
UNSAFE_OP_IN_UNSAFE_FN,
561582
hir_id,
562583
span,
563-
UnsafeOpInUnsafeFnCallToUnsafeFunctionRequiresUnsafeNameless { span },
584+
UnsafeOpInUnsafeFnCallToUnsafeFunctionRequiresUnsafeNameless {
585+
span,
586+
unsafe_not_inherited_note,
587+
},
564588
),
565589
UseOfInlineAssembly => tcx.emit_spanned_lint(
566590
UNSAFE_OP_IN_UNSAFE_FN,
567591
hir_id,
568592
span,
569-
UnsafeOpInUnsafeFnUseOfInlineAssemblyRequiresUnsafe { span },
593+
UnsafeOpInUnsafeFnUseOfInlineAssemblyRequiresUnsafe {
594+
span,
595+
unsafe_not_inherited_note,
596+
},
570597
),
571598
InitializingTypeWith => tcx.emit_spanned_lint(
572599
UNSAFE_OP_IN_UNSAFE_FN,
573600
hir_id,
574601
span,
575-
UnsafeOpInUnsafeFnInitializingTypeWithRequiresUnsafe { span },
602+
UnsafeOpInUnsafeFnInitializingTypeWithRequiresUnsafe {
603+
span,
604+
unsafe_not_inherited_note,
605+
},
576606
),
577607
UseOfMutableStatic => tcx.emit_spanned_lint(
578608
UNSAFE_OP_IN_UNSAFE_FN,
579609
hir_id,
580610
span,
581-
UnsafeOpInUnsafeFnUseOfMutableStaticRequiresUnsafe { span },
611+
UnsafeOpInUnsafeFnUseOfMutableStaticRequiresUnsafe {
612+
span,
613+
unsafe_not_inherited_note,
614+
},
582615
),
583616
UseOfExternStatic => tcx.emit_spanned_lint(
584617
UNSAFE_OP_IN_UNSAFE_FN,
585618
hir_id,
586619
span,
587-
UnsafeOpInUnsafeFnUseOfExternStaticRequiresUnsafe { span },
620+
UnsafeOpInUnsafeFnUseOfExternStaticRequiresUnsafe {
621+
span,
622+
unsafe_not_inherited_note,
623+
},
588624
),
589625
DerefOfRawPointer => tcx.emit_spanned_lint(
590626
UNSAFE_OP_IN_UNSAFE_FN,
591627
hir_id,
592628
span,
593-
UnsafeOpInUnsafeFnDerefOfRawPointerRequiresUnsafe { span },
629+
UnsafeOpInUnsafeFnDerefOfRawPointerRequiresUnsafe {
630+
span,
631+
unsafe_not_inherited_note,
632+
},
594633
),
595634
AccessToUnionField => tcx.emit_spanned_lint(
596635
UNSAFE_OP_IN_UNSAFE_FN,
597636
hir_id,
598637
span,
599-
UnsafeOpInUnsafeFnAccessToUnionFieldRequiresUnsafe { span },
638+
UnsafeOpInUnsafeFnAccessToUnionFieldRequiresUnsafe {
639+
span,
640+
unsafe_not_inherited_note,
641+
},
600642
),
601643
MutationOfLayoutConstrainedField => tcx.emit_spanned_lint(
602644
UNSAFE_OP_IN_UNSAFE_FN,
603645
hir_id,
604646
span,
605-
UnsafeOpInUnsafeFnMutationOfLayoutConstrainedFieldRequiresUnsafe { span },
647+
UnsafeOpInUnsafeFnMutationOfLayoutConstrainedFieldRequiresUnsafe {
648+
span,
649+
unsafe_not_inherited_note,
650+
},
606651
),
607652
BorrowOfLayoutConstrainedField => tcx.emit_spanned_lint(
608653
UNSAFE_OP_IN_UNSAFE_FN,
609654
hir_id,
610655
span,
611-
UnsafeOpInUnsafeFnBorrowOfLayoutConstrainedFieldRequiresUnsafe { span },
656+
UnsafeOpInUnsafeFnBorrowOfLayoutConstrainedFieldRequiresUnsafe {
657+
span,
658+
unsafe_not_inherited_note,
659+
},
612660
),
613661
CallToFunctionWith(did) => tcx.emit_spanned_lint(
614662
UNSAFE_OP_IN_UNSAFE_FN,
@@ -617,6 +665,7 @@ impl UnsafeOpKind {
617665
UnsafeOpInUnsafeFnCallToFunctionWithRequiresUnsafe {
618666
span,
619667
function: &with_no_trimmed_paths!(tcx.def_path_str(*did)),
668+
unsafe_not_inherited_note,
620669
},
621670
),
622671
}
@@ -831,6 +880,7 @@ pub fn thir_check_unsafety(tcx: TyCtxt<'_>, def: LocalDefId) {
831880
param_env: tcx.param_env(def),
832881
inside_adt: false,
833882
warnings: &mut warnings,
883+
suggest_unsafe_block: true,
834884
};
835885
visitor.visit_expr(&thir[expr]);
836886

compiler/rustc_mir_build/src/errors.rs

+43
Original file line numberDiff line numberDiff line change
@@ -29,6 +29,8 @@ pub struct UnsafeOpInUnsafeFnCallToUnsafeFunctionRequiresUnsafe<'a> {
2929
#[label]
3030
pub span: Span,
3131
pub function: &'a str,
32+
#[subdiagnostic]
33+
pub unsafe_not_inherited_note: Option<UnsafeNotInheritedLintNote>,
3234
}
3335

3436
#[derive(LintDiagnostic)]
@@ -37,6 +39,8 @@ pub struct UnsafeOpInUnsafeFnCallToUnsafeFunctionRequiresUnsafe<'a> {
3739
pub struct UnsafeOpInUnsafeFnCallToUnsafeFunctionRequiresUnsafeNameless {
3840
#[label]
3941
pub span: Span,
42+
#[subdiagnostic]
43+
pub unsafe_not_inherited_note: Option<UnsafeNotInheritedLintNote>,
4044
}
4145

4246
#[derive(LintDiagnostic)]
@@ -45,6 +49,8 @@ pub struct UnsafeOpInUnsafeFnCallToUnsafeFunctionRequiresUnsafeNameless {
4549
pub struct UnsafeOpInUnsafeFnUseOfInlineAssemblyRequiresUnsafe {
4650
#[label]
4751
pub span: Span,
52+
#[subdiagnostic]
53+
pub unsafe_not_inherited_note: Option<UnsafeNotInheritedLintNote>,
4854
}
4955

5056
#[derive(LintDiagnostic)]
@@ -53,6 +59,8 @@ pub struct UnsafeOpInUnsafeFnUseOfInlineAssemblyRequiresUnsafe {
5359
pub struct UnsafeOpInUnsafeFnInitializingTypeWithRequiresUnsafe {
5460
#[label]
5561
pub span: Span,
62+
#[subdiagnostic]
63+
pub unsafe_not_inherited_note: Option<UnsafeNotInheritedLintNote>,
5664
}
5765

5866
#[derive(LintDiagnostic)]
@@ -61,6 +69,8 @@ pub struct UnsafeOpInUnsafeFnInitializingTypeWithRequiresUnsafe {
6169
pub struct UnsafeOpInUnsafeFnUseOfMutableStaticRequiresUnsafe {
6270
#[label]
6371
pub span: Span,
72+
#[subdiagnostic]
73+
pub unsafe_not_inherited_note: Option<UnsafeNotInheritedLintNote>,
6474
}
6575

6676
#[derive(LintDiagnostic)]
@@ -69,6 +79,8 @@ pub struct UnsafeOpInUnsafeFnUseOfMutableStaticRequiresUnsafe {
6979
pub struct UnsafeOpInUnsafeFnUseOfExternStaticRequiresUnsafe {
7080
#[label]
7181
pub span: Span,
82+
#[subdiagnostic]
83+
pub unsafe_not_inherited_note: Option<UnsafeNotInheritedLintNote>,
7284
}
7385

7486
#[derive(LintDiagnostic)]
@@ -77,6 +89,8 @@ pub struct UnsafeOpInUnsafeFnUseOfExternStaticRequiresUnsafe {
7789
pub struct UnsafeOpInUnsafeFnDerefOfRawPointerRequiresUnsafe {
7890
#[label]
7991
pub span: Span,
92+
#[subdiagnostic]
93+
pub unsafe_not_inherited_note: Option<UnsafeNotInheritedLintNote>,
8094
}
8195

8296
#[derive(LintDiagnostic)]
@@ -85,6 +99,8 @@ pub struct UnsafeOpInUnsafeFnDerefOfRawPointerRequiresUnsafe {
8599
pub struct UnsafeOpInUnsafeFnAccessToUnionFieldRequiresUnsafe {
86100
#[label]
87101
pub span: Span,
102+
#[subdiagnostic]
103+
pub unsafe_not_inherited_note: Option<UnsafeNotInheritedLintNote>,
88104
}
89105

90106
#[derive(LintDiagnostic)]
@@ -93,13 +109,17 @@ pub struct UnsafeOpInUnsafeFnAccessToUnionFieldRequiresUnsafe {
93109
pub struct UnsafeOpInUnsafeFnMutationOfLayoutConstrainedFieldRequiresUnsafe {
94110
#[label]
95111
pub span: Span,
112+
#[subdiagnostic]
113+
pub unsafe_not_inherited_note: Option<UnsafeNotInheritedLintNote>,
96114
}
97115

98116
#[derive(LintDiagnostic)]
99117
#[diag(mir_build_unsafe_op_in_unsafe_fn_borrow_of_layout_constrained_field_requires_unsafe)]
100118
pub struct UnsafeOpInUnsafeFnBorrowOfLayoutConstrainedFieldRequiresUnsafe {
101119
#[label]
102120
pub span: Span,
121+
#[subdiagnostic]
122+
pub unsafe_not_inherited_note: Option<UnsafeNotInheritedLintNote>,
103123
}
104124

105125
#[derive(LintDiagnostic)]
@@ -109,6 +129,8 @@ pub struct UnsafeOpInUnsafeFnCallToFunctionWithRequiresUnsafe<'a> {
109129
#[label]
110130
pub span: Span,
111131
pub function: &'a str,
132+
#[subdiagnostic]
133+
pub unsafe_not_inherited_note: Option<UnsafeNotInheritedLintNote>,
112134
}
113135

114136
#[derive(Diagnostic)]
@@ -376,6 +398,27 @@ pub struct UnsafeNotInheritedNote {
376398
pub span: Span,
377399
}
378400

401+
pub struct UnsafeNotInheritedLintNote {
402+
pub signature_span: Span,
403+
pub body_span: Span,
404+
}
405+
406+
impl AddToDiagnostic for UnsafeNotInheritedLintNote {
407+
fn add_to_diagnostic_with<F>(self, diag: &mut Diagnostic, _: F)
408+
where
409+
F: Fn(&mut Diagnostic, SubdiagnosticMessage) -> SubdiagnosticMessage,
410+
{
411+
diag.span_note(self.signature_span, fluent::mir_build_unsafe_fn_safe_body);
412+
let body_start = self.body_span.shrink_to_lo();
413+
let body_end = self.body_span.shrink_to_hi();
414+
diag.tool_only_multipart_suggestion(
415+
fluent::mir_build_wrap_suggestion,
416+
vec![(body_start, "{ unsafe ".into()), (body_end, "}".into())],
417+
Applicability::MaybeIncorrect,
418+
);
419+
}
420+
}
421+
379422
#[derive(LintDiagnostic)]
380423
#[diag(mir_build_unused_unsafe)]
381424
pub struct UnusedUnsafe {

src/tools/compiletest/src/runtest.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -3962,7 +3962,7 @@ impl<'test> TestCx<'test> {
39623962
// And finally, compile the fixed code and make sure it both
39633963
// succeeds and has no diagnostics.
39643964
let rustc = self.make_compile_args(
3965-
&self.testpaths.file.with_extension(UI_FIXED),
3965+
&self.expected_output_path(UI_FIXED),
39663966
TargetLocation::ThisFile(self.make_exe_name()),
39673967
emit_metadata,
39683968
AllowUnused::No,

0 commit comments

Comments
 (0)