Skip to content

Commit ec8619d

Browse files
committed
Auto merge of #96294 - Emilgardis:def_id-in-unsafetyviolationdetails, r=oli-obk
Display function path in unsafety violations - E0133 adds `DefId` to `UnsafetyViolationDetails` this enables consumers to access the function definition that was reported to be unsafe and also changes the output for some E0133 diagnostics
2 parents 055bf4c + f71597c commit ec8619d

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

42 files changed

+211
-142
lines changed

compiler/rustc_middle/src/mir/query.rs

+49-19
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,7 @@ use rustc_index::vec::IndexVec;
1212
use rustc_span::Span;
1313
use rustc_target::abi::VariantIdx;
1414
use smallvec::SmallVec;
15+
use std::borrow::Cow;
1516
use std::cell::Cell;
1617
use std::fmt::{self, Debug};
1718

@@ -28,7 +29,7 @@ pub enum UnsafetyViolationKind {
2829

2930
#[derive(Copy, Clone, PartialEq, TyEncodable, TyDecodable, HashStable, Debug)]
3031
pub enum UnsafetyViolationDetails {
31-
CallToUnsafeFunction,
32+
CallToUnsafeFunction(Option<DefId>),
3233
UseOfInlineAssembly,
3334
InitializingTypeWith,
3435
CastOfPointerToInt,
@@ -39,66 +40,95 @@ pub enum UnsafetyViolationDetails {
3940
AccessToUnionField,
4041
MutationOfLayoutConstrainedField,
4142
BorrowOfLayoutConstrainedField,
42-
CallToFunctionWith,
43+
CallToFunctionWith(DefId),
4344
}
4445

4546
impl UnsafetyViolationDetails {
46-
pub fn description_and_note(&self) -> (&'static str, &'static str) {
47+
pub fn simple_description(&self) -> &'static str {
48+
use UnsafetyViolationDetails::*;
49+
50+
match self {
51+
CallToUnsafeFunction(..) => "call to unsafe function",
52+
UseOfInlineAssembly => "use of inline assembly",
53+
InitializingTypeWith => "initializing type with `rustc_layout_scalar_valid_range` attr",
54+
CastOfPointerToInt => "cast of pointer to int",
55+
UseOfMutableStatic => "use of mutable static",
56+
UseOfExternStatic => "use of extern static",
57+
DerefOfRawPointer => "dereference of raw pointer",
58+
AssignToDroppingUnionField => "assignment to union field that might need dropping",
59+
AccessToUnionField => "access to union field",
60+
MutationOfLayoutConstrainedField => "mutation of layout constrained field",
61+
BorrowOfLayoutConstrainedField => {
62+
"borrow of layout constrained field with interior mutability"
63+
}
64+
CallToFunctionWith(..) => "call to function with `#[target_feature]`",
65+
}
66+
}
67+
68+
pub fn description_and_note(&self, tcx: TyCtxt<'_>) -> (Cow<'static, str>, &'static str) {
4769
use UnsafetyViolationDetails::*;
4870
match self {
49-
CallToUnsafeFunction => (
50-
"call to unsafe function",
71+
CallToUnsafeFunction(did) => (
72+
if let Some(did) = did {
73+
Cow::from(format!("call to unsafe function `{}`", tcx.def_path_str(*did)))
74+
} else {
75+
Cow::Borrowed(self.simple_description())
76+
},
5177
"consult the function's documentation for information on how to avoid undefined \
5278
behavior",
5379
),
5480
UseOfInlineAssembly => (
55-
"use of inline assembly",
81+
Cow::Borrowed(self.simple_description()),
5682
"inline assembly is entirely unchecked and can cause undefined behavior",
5783
),
5884
InitializingTypeWith => (
59-
"initializing type with `rustc_layout_scalar_valid_range` attr",
85+
Cow::Borrowed(self.simple_description()),
6086
"initializing a layout restricted type's field with a value outside the valid \
6187
range is undefined behavior",
6288
),
63-
CastOfPointerToInt => {
64-
("cast of pointer to int", "casting pointers to integers in constants")
65-
}
89+
CastOfPointerToInt => (
90+
Cow::Borrowed(self.simple_description()),
91+
"casting pointers to integers in constants",
92+
),
6693
UseOfMutableStatic => (
67-
"use of mutable static",
94+
Cow::Borrowed(self.simple_description()),
6895
"mutable statics can be mutated by multiple threads: aliasing violations or data \
6996
races will cause undefined behavior",
7097
),
7198
UseOfExternStatic => (
72-
"use of extern static",
99+
Cow::Borrowed(self.simple_description()),
73100
"extern statics are not controlled by the Rust type system: invalid data, \
74101
aliasing violations or data races will cause undefined behavior",
75102
),
76103
DerefOfRawPointer => (
77-
"dereference of raw pointer",
104+
Cow::Borrowed(self.simple_description()),
78105
"raw pointers may be null, dangling or unaligned; they can violate aliasing rules \
79106
and cause data races: all of these are undefined behavior",
80107
),
81108
AssignToDroppingUnionField => (
82-
"assignment to union field that might need dropping",
109+
Cow::Borrowed(self.simple_description()),
83110
"the previous content of the field will be dropped, which causes undefined \
84111
behavior if the field was not properly initialized",
85112
),
86113
AccessToUnionField => (
87-
"access to union field",
114+
Cow::Borrowed(self.simple_description()),
88115
"the field may not be properly initialized: using uninitialized data will cause \
89116
undefined behavior",
90117
),
91118
MutationOfLayoutConstrainedField => (
92-
"mutation of layout constrained field",
119+
Cow::Borrowed(self.simple_description()),
93120
"mutating layout constrained fields cannot statically be checked for valid values",
94121
),
95122
BorrowOfLayoutConstrainedField => (
96-
"borrow of layout constrained field with interior mutability",
123+
Cow::Borrowed(self.simple_description()),
97124
"references to fields of layout constrained fields lose the constraints. Coupled \
98125
with interior mutability, the field can be changed to invalid values",
99126
),
100-
CallToFunctionWith => (
101-
"call to function with `#[target_feature]`",
127+
CallToFunctionWith(did) => (
128+
Cow::from(format!(
129+
"call to function `{}` with `#[target_feature]`",
130+
tcx.def_path_str(*did)
131+
)),
102132
"can only be called if the required target features are available",
103133
),
104134
}

compiler/rustc_mir_build/src/check_unsafety.rs

+53-21
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,7 @@ use rustc_span::def_id::{DefId, LocalDefId};
1212
use rustc_span::symbol::Symbol;
1313
use rustc_span::Span;
1414

15+
use std::borrow::Cow;
1516
use std::ops::Bound;
1617

1718
struct UnsafetyVisitor<'a, 'tcx> {
@@ -70,7 +71,6 @@ impl<'tcx> UnsafetyVisitor<'_, 'tcx> {
7071
}
7172

7273
fn requires_unsafe(&mut self, span: Span, kind: UnsafeOpKind) {
73-
let (description, note) = kind.description_and_note();
7474
let unsafe_op_in_unsafe_fn_allowed = self.unsafe_op_in_unsafe_fn_allowed();
7575
match self.safety_context {
7676
SafetyContext::BuiltinUnsafeBlock => {}
@@ -82,6 +82,7 @@ impl<'tcx> UnsafetyVisitor<'_, 'tcx> {
8282
}
8383
SafetyContext::UnsafeFn if unsafe_op_in_unsafe_fn_allowed => {}
8484
SafetyContext::UnsafeFn => {
85+
let (description, note) = kind.description_and_note(self.tcx);
8586
// unsafe_op_in_unsafe_fn is disallowed
8687
self.tcx.struct_span_lint_hir(
8788
UNSAFE_OP_IN_UNSAFE_FN,
@@ -92,13 +93,14 @@ impl<'tcx> UnsafetyVisitor<'_, 'tcx> {
9293
"{} is unsafe and requires unsafe block (error E0133)",
9394
description,
9495
))
95-
.span_label(span, description)
96+
.span_label(span, kind.simple_description())
9697
.note(note)
9798
.emit();
9899
},
99100
)
100101
}
101102
SafetyContext::Safe => {
103+
let (description, note) = kind.description_and_note(self.tcx);
102104
let fn_sugg = if unsafe_op_in_unsafe_fn_allowed { " function or" } else { "" };
103105
struct_span_err!(
104106
self.tcx.sess,
@@ -108,7 +110,7 @@ impl<'tcx> UnsafetyVisitor<'_, 'tcx> {
108110
description,
109111
fn_sugg,
110112
)
111-
.span_label(span, description)
113+
.span_label(span, kind.simple_description())
112114
.note(note)
113115
.emit();
114116
}
@@ -350,7 +352,12 @@ impl<'a, 'tcx> Visitor<'a, 'tcx> for UnsafetyVisitor<'a, 'tcx> {
350352
}
351353
ExprKind::Call { fun, ty: _, args: _, from_hir_call: _, fn_span: _ } => {
352354
if self.thir[fun].ty.fn_sig(self.tcx).unsafety() == hir::Unsafety::Unsafe {
353-
self.requires_unsafe(expr.span, CallToUnsafeFunction);
355+
let func_id = if let ty::FnDef(func_id, _) = self.thir[fun].ty.kind() {
356+
Some(*func_id)
357+
} else {
358+
None
359+
};
360+
self.requires_unsafe(expr.span, CallToUnsafeFunction(func_id));
354361
} else if let &ty::FnDef(func_did, _) = self.thir[fun].ty.kind() {
355362
// If the called function has target features the calling function hasn't,
356363
// the call requires `unsafe`. Don't check this on wasm
@@ -364,7 +371,7 @@ impl<'a, 'tcx> Visitor<'a, 'tcx> for UnsafetyVisitor<'a, 'tcx> {
364371
.iter()
365372
.all(|feature| self.body_target_features.contains(feature))
366373
{
367-
self.requires_unsafe(expr.span, CallToFunctionWith);
374+
self.requires_unsafe(expr.span, CallToFunctionWith(func_did));
368375
}
369376
}
370377
}
@@ -523,7 +530,7 @@ impl BodyUnsafety {
523530

524531
#[derive(Clone, Copy, PartialEq)]
525532
enum UnsafeOpKind {
526-
CallToUnsafeFunction,
533+
CallToUnsafeFunction(Option<DefId>),
527534
UseOfInlineAssembly,
528535
InitializingTypeWith,
529536
UseOfMutableStatic,
@@ -533,64 +540,89 @@ enum UnsafeOpKind {
533540
AccessToUnionField,
534541
MutationOfLayoutConstrainedField,
535542
BorrowOfLayoutConstrainedField,
536-
CallToFunctionWith,
543+
CallToFunctionWith(DefId),
537544
}
538545

539546
use UnsafeOpKind::*;
540547

541548
impl UnsafeOpKind {
542-
pub fn description_and_note(&self) -> (&'static str, &'static str) {
549+
pub fn simple_description(&self) -> &'static str {
543550
match self {
544-
CallToUnsafeFunction => (
545-
"call to unsafe function",
551+
CallToUnsafeFunction(..) => "call to unsafe function",
552+
UseOfInlineAssembly => "use of inline assembly",
553+
InitializingTypeWith => "initializing type with `rustc_layout_scalar_valid_range` attr",
554+
UseOfMutableStatic => "use of mutable static",
555+
UseOfExternStatic => "use of extern static",
556+
DerefOfRawPointer => "dereference of raw pointer",
557+
AssignToDroppingUnionField => "assignment to union field that might need dropping",
558+
AccessToUnionField => "access to union field",
559+
MutationOfLayoutConstrainedField => "mutation of layout constrained field",
560+
BorrowOfLayoutConstrainedField => {
561+
"borrow of layout constrained field with interior mutability"
562+
}
563+
CallToFunctionWith(..) => "call to function with `#[target_feature]`",
564+
}
565+
}
566+
567+
pub fn description_and_note(&self, tcx: TyCtxt<'_>) -> (Cow<'static, str>, &'static str) {
568+
match self {
569+
CallToUnsafeFunction(did) => (
570+
if let Some(did) = did {
571+
Cow::from(format!("call to unsafe function `{}`", tcx.def_path_str(*did)))
572+
} else {
573+
Cow::Borrowed(self.simple_description())
574+
},
546575
"consult the function's documentation for information on how to avoid undefined \
547576
behavior",
548577
),
549578
UseOfInlineAssembly => (
550-
"use of inline assembly",
579+
Cow::Borrowed(self.simple_description()),
551580
"inline assembly is entirely unchecked and can cause undefined behavior",
552581
),
553582
InitializingTypeWith => (
554-
"initializing type with `rustc_layout_scalar_valid_range` attr",
583+
Cow::Borrowed(self.simple_description()),
555584
"initializing a layout restricted type's field with a value outside the valid \
556585
range is undefined behavior",
557586
),
558587
UseOfMutableStatic => (
559-
"use of mutable static",
588+
Cow::Borrowed(self.simple_description()),
560589
"mutable statics can be mutated by multiple threads: aliasing violations or data \
561590
races will cause undefined behavior",
562591
),
563592
UseOfExternStatic => (
564-
"use of extern static",
593+
Cow::Borrowed(self.simple_description()),
565594
"extern statics are not controlled by the Rust type system: invalid data, \
566595
aliasing violations or data races will cause undefined behavior",
567596
),
568597
DerefOfRawPointer => (
569-
"dereference of raw pointer",
598+
Cow::Borrowed(self.simple_description()),
570599
"raw pointers may be null, dangling or unaligned; they can violate aliasing rules \
571600
and cause data races: all of these are undefined behavior",
572601
),
573602
AssignToDroppingUnionField => (
574-
"assignment to union field that might need dropping",
603+
Cow::Borrowed(self.simple_description()),
575604
"the previous content of the field will be dropped, which causes undefined \
576605
behavior if the field was not properly initialized",
577606
),
578607
AccessToUnionField => (
579-
"access to union field",
608+
Cow::Borrowed(self.simple_description()),
580609
"the field may not be properly initialized: using uninitialized data will cause \
581610
undefined behavior",
582611
),
583612
MutationOfLayoutConstrainedField => (
584-
"mutation of layout constrained field",
613+
Cow::Borrowed(self.simple_description()),
585614
"mutating layout constrained fields cannot statically be checked for valid values",
586615
),
587616
BorrowOfLayoutConstrainedField => (
588-
"borrow of layout constrained field with interior mutability",
617+
Cow::Borrowed(self.simple_description()),
589618
"references to fields of layout constrained fields lose the constraints. Coupled \
590619
with interior mutability, the field can be changed to invalid values",
591620
),
592-
CallToFunctionWith => (
593-
"call to function with `#[target_feature]`",
621+
CallToFunctionWith(did) => (
622+
Cow::from(format!(
623+
"call to function `{}` with `#[target_feature]`",
624+
tcx.def_path_str(*did)
625+
)),
594626
"can only be called if the required target features are available",
595627
),
596628
}

compiler/rustc_mir_transform/src/check_unsafety.rs

+8-5
Original file line numberDiff line numberDiff line change
@@ -70,15 +70,17 @@ impl<'tcx> Visitor<'tcx> for UnsafetyChecker<'_, 'tcx> {
7070

7171
TerminatorKind::Call { ref func, .. } => {
7272
let func_ty = func.ty(self.body, self.tcx);
73+
let func_id =
74+
if let ty::FnDef(func_id, _) = func_ty.kind() { Some(func_id) } else { None };
7375
let sig = func_ty.fn_sig(self.tcx);
7476
if let hir::Unsafety::Unsafe = sig.unsafety() {
7577
self.require_unsafe(
7678
UnsafetyViolationKind::General,
77-
UnsafetyViolationDetails::CallToUnsafeFunction,
79+
UnsafetyViolationDetails::CallToUnsafeFunction(func_id.copied()),
7880
)
7981
}
8082

81-
if let ty::FnDef(func_id, _) = func_ty.kind() {
83+
if let Some(func_id) = func_id {
8284
self.check_target_features(*func_id);
8385
}
8486
}
@@ -379,7 +381,7 @@ impl<'tcx> UnsafetyChecker<'_, 'tcx> {
379381
if !callee_features.iter().all(|feature| self_features.contains(feature)) {
380382
self.require_unsafe(
381383
UnsafetyViolationKind::General,
382-
UnsafetyViolationDetails::CallToFunctionWith,
384+
UnsafetyViolationDetails::CallToFunctionWith(func_did),
383385
)
384386
}
385387
}
@@ -578,7 +580,8 @@ pub fn check_unsafety(tcx: TyCtxt<'_>, def_id: LocalDefId) {
578580
let UnsafetyCheckResult { violations, unused_unsafes, .. } = tcx.unsafety_check_result(def_id);
579581

580582
for &UnsafetyViolation { source_info, lint_root, kind, details } in violations.iter() {
581-
let (description, note) = details.description_and_note();
583+
let (description, note) =
584+
ty::print::with_no_trimmed_paths!(details.description_and_note(tcx));
582585

583586
// Report an error.
584587
let unsafe_fn_msg =
@@ -595,7 +598,7 @@ pub fn check_unsafety(tcx: TyCtxt<'_>, def_id: LocalDefId) {
595598
description,
596599
unsafe_fn_msg,
597600
)
598-
.span_label(source_info.span, description)
601+
.span_label(source_info.span, details.simple_description())
599602
.note(note)
600603
.emit();
601604
}

src/test/ui/async-await/async-unsafe-fn-call-in-safe.mir.stderr

+4-4
Original file line numberDiff line numberDiff line change
@@ -1,28 +1,28 @@
1-
error[E0133]: call to unsafe function is unsafe and requires unsafe function or block
1+
error[E0133]: call to unsafe function `S::f` is unsafe and requires unsafe function or block
22
--> $DIR/async-unsafe-fn-call-in-safe.rs:14:5
33
|
44
LL | S::f();
55
| ^^^^^^ call to unsafe function
66
|
77
= note: consult the function's documentation for information on how to avoid undefined behavior
88

9-
error[E0133]: call to unsafe function is unsafe and requires unsafe function or block
9+
error[E0133]: call to unsafe function `f` is unsafe and requires unsafe function or block
1010
--> $DIR/async-unsafe-fn-call-in-safe.rs:15:5
1111
|
1212
LL | f();
1313
| ^^^ call to unsafe function
1414
|
1515
= note: consult the function's documentation for information on how to avoid undefined behavior
1616

17-
error[E0133]: call to unsafe function is unsafe and requires unsafe function or block
17+
error[E0133]: call to unsafe function `S::f` is unsafe and requires unsafe function or block
1818
--> $DIR/async-unsafe-fn-call-in-safe.rs:19:5
1919
|
2020
LL | S::f();
2121
| ^^^^^^ call to unsafe function
2222
|
2323
= note: consult the function's documentation for information on how to avoid undefined behavior
2424

25-
error[E0133]: call to unsafe function is unsafe and requires unsafe function or block
25+
error[E0133]: call to unsafe function `f` is unsafe and requires unsafe function or block
2626
--> $DIR/async-unsafe-fn-call-in-safe.rs:20:5
2727
|
2828
LL | f();

0 commit comments

Comments
 (0)