]> git.lizzy.rs Git - rust.git/blob - src/librustc_mir/transform/check_unsafety.rs
Rollup merge of #67909 - varkor:obsolete-const-print, r=davidtwco
[rust.git] / src / librustc_mir / transform / check_unsafety.rs
1 use rustc::hir::intravisit;
2 use rustc::lint::builtin::{SAFE_PACKED_BORROWS, UNUSED_UNSAFE};
3 use rustc::mir::visit::{MutatingUseContext, PlaceContext, Visitor};
4 use rustc::mir::*;
5 use rustc::ty::cast::CastTy;
6 use rustc::ty::query::Providers;
7 use rustc::ty::{self, TyCtxt};
8 use rustc_data_structures::fx::FxHashSet;
9 use rustc_hir as hir;
10 use rustc_hir::def_id::DefId;
11 use rustc_hir::Node;
12 use rustc_span::symbol::{sym, Symbol};
13
14 use std::ops::Bound;
15
16 use crate::util;
17
18 use rustc_error_codes::*;
19
20 pub struct UnsafetyChecker<'a, 'tcx> {
21     body: &'a Body<'tcx>,
22     const_context: bool,
23     min_const_fn: bool,
24     violations: Vec<UnsafetyViolation>,
25     source_info: SourceInfo,
26     tcx: TyCtxt<'tcx>,
27     param_env: ty::ParamEnv<'tcx>,
28     /// Mark an `unsafe` block as used, so we don't lint it.
29     used_unsafe: FxHashSet<hir::HirId>,
30     inherited_blocks: Vec<(hir::HirId, bool)>,
31 }
32
33 impl<'a, 'tcx> UnsafetyChecker<'a, 'tcx> {
34     fn new(
35         const_context: bool,
36         min_const_fn: bool,
37         body: &'a Body<'tcx>,
38         tcx: TyCtxt<'tcx>,
39         param_env: ty::ParamEnv<'tcx>,
40     ) -> Self {
41         // sanity check
42         if min_const_fn {
43             assert!(const_context);
44         }
45         Self {
46             body,
47             const_context,
48             min_const_fn,
49             violations: vec![],
50             source_info: SourceInfo { span: body.span, scope: OUTERMOST_SOURCE_SCOPE },
51             tcx,
52             param_env,
53             used_unsafe: Default::default(),
54             inherited_blocks: vec![],
55         }
56     }
57 }
58
59 impl<'a, 'tcx> Visitor<'tcx> for UnsafetyChecker<'a, 'tcx> {
60     fn visit_terminator(&mut self, terminator: &Terminator<'tcx>, location: Location) {
61         self.source_info = terminator.source_info;
62         match terminator.kind {
63             TerminatorKind::Goto { .. }
64             | TerminatorKind::SwitchInt { .. }
65             | TerminatorKind::Drop { .. }
66             | TerminatorKind::Yield { .. }
67             | TerminatorKind::Assert { .. }
68             | TerminatorKind::DropAndReplace { .. }
69             | TerminatorKind::GeneratorDrop
70             | TerminatorKind::Resume
71             | TerminatorKind::Abort
72             | TerminatorKind::Return
73             | TerminatorKind::Unreachable
74             | TerminatorKind::FalseEdges { .. }
75             | TerminatorKind::FalseUnwind { .. } => {
76                 // safe (at least as emitted during MIR construction)
77             }
78
79             TerminatorKind::Call { ref func, .. } => {
80                 let func_ty = func.ty(self.body, self.tcx);
81                 let sig = func_ty.fn_sig(self.tcx);
82                 if let hir::Unsafety::Unsafe = sig.unsafety() {
83                     self.require_unsafe(
84                         "call to unsafe function",
85                         "consult the function's documentation for information on how to avoid \
86                          undefined behavior",
87                         UnsafetyViolationKind::GeneralAndConstFn,
88                     )
89                 }
90             }
91         }
92         self.super_terminator(terminator, location);
93     }
94
95     fn visit_statement(&mut self, statement: &Statement<'tcx>, location: Location) {
96         self.source_info = statement.source_info;
97         match statement.kind {
98             StatementKind::Assign(..)
99             | StatementKind::FakeRead(..)
100             | StatementKind::SetDiscriminant { .. }
101             | StatementKind::StorageLive(..)
102             | StatementKind::StorageDead(..)
103             | StatementKind::Retag { .. }
104             | StatementKind::AscribeUserType(..)
105             | StatementKind::Nop => {
106                 // safe (at least as emitted during MIR construction)
107             }
108
109             StatementKind::InlineAsm { .. } => self.require_unsafe(
110                 "use of inline assembly",
111                 "inline assembly is entirely unchecked and can cause undefined behavior",
112                 UnsafetyViolationKind::General,
113             ),
114         }
115         self.super_statement(statement, location);
116     }
117
118     fn visit_rvalue(&mut self, rvalue: &Rvalue<'tcx>, location: Location) {
119         match rvalue {
120             Rvalue::Aggregate(box ref aggregate, _) => match aggregate {
121                 &AggregateKind::Array(..) | &AggregateKind::Tuple => {}
122                 &AggregateKind::Adt(ref def, ..) => {
123                     match self.tcx.layout_scalar_valid_range(def.did) {
124                         (Bound::Unbounded, Bound::Unbounded) => {}
125                         _ => self.require_unsafe(
126                             "initializing type with `rustc_layout_scalar_valid_range` attr",
127                             "initializing a layout restricted type's field with a value \
128                                 outside the valid range is undefined behavior",
129                             UnsafetyViolationKind::GeneralAndConstFn,
130                         ),
131                     }
132                 }
133                 &AggregateKind::Closure(def_id, _) | &AggregateKind::Generator(def_id, _, _) => {
134                     let UnsafetyCheckResult { violations, unsafe_blocks } =
135                         self.tcx.unsafety_check_result(def_id);
136                     self.register_violations(&violations, &unsafe_blocks);
137                 }
138             },
139             // casting pointers to ints is unsafe in const fn because the const evaluator cannot
140             // possibly know what the result of various operations like `address / 2` would be
141             // pointers during const evaluation have no integral address, only an abstract one
142             Rvalue::Cast(CastKind::Misc, ref operand, cast_ty)
143                 if self.const_context && self.tcx.features().const_raw_ptr_to_usize_cast =>
144             {
145                 let operand_ty = operand.ty(self.body, self.tcx);
146                 let cast_in = CastTy::from_ty(operand_ty).expect("bad input type for cast");
147                 let cast_out = CastTy::from_ty(cast_ty).expect("bad output type for cast");
148                 match (cast_in, cast_out) {
149                     (CastTy::Ptr(_), CastTy::Int(_)) | (CastTy::FnPtr, CastTy::Int(_)) => {
150                         self.register_violations(
151                             &[UnsafetyViolation {
152                                 source_info: self.source_info,
153                                 description: Symbol::intern("cast of pointer to int"),
154                                 details: Symbol::intern(
155                                     "casting pointers to integers in constants",
156                                 ),
157                                 kind: UnsafetyViolationKind::General,
158                             }],
159                             &[],
160                         );
161                     }
162                     _ => {}
163                 }
164             }
165             // raw pointer and fn pointer operations are unsafe as it is not clear whether one
166             // pointer would be "less" or "equal" to another, because we cannot know where llvm
167             // or the linker will place various statics in memory. Without this information the
168             // result of a comparison of addresses would differ between runtime and compile-time.
169             Rvalue::BinaryOp(_, ref lhs, _)
170                 if self.const_context && self.tcx.features().const_compare_raw_pointers =>
171             {
172                 if let ty::RawPtr(_) | ty::FnPtr(..) = lhs.ty(self.body, self.tcx).kind {
173                     self.register_violations(
174                         &[UnsafetyViolation {
175                             source_info: self.source_info,
176                             description: Symbol::intern("pointer operation"),
177                             details: Symbol::intern("operations on pointers in constants"),
178                             kind: UnsafetyViolationKind::General,
179                         }],
180                         &[],
181                     );
182                 }
183             }
184             _ => {}
185         }
186         self.super_rvalue(rvalue, location);
187     }
188
189     fn visit_place(&mut self, place: &Place<'tcx>, context: PlaceContext, _location: Location) {
190         match place.base {
191             PlaceBase::Local(..) => {
192                 // Locals are safe.
193             }
194             PlaceBase::Static(box Static { kind: StaticKind::Promoted(_, _), .. }) => {
195                 bug!("unsafety checking should happen before promotion");
196             }
197             PlaceBase::Static(box Static { kind: StaticKind::Static, .. }) => {
198                 bug!("StaticKind::Static should not exist");
199             }
200         }
201
202         for (i, elem) in place.projection.iter().enumerate() {
203             let proj_base = &place.projection[..i];
204
205             if context.is_borrow() {
206                 if util::is_disaligned(self.tcx, self.body, self.param_env, place) {
207                     let source_info = self.source_info;
208                     let lint_root = self.body.source_scopes[source_info.scope]
209                         .local_data
210                         .as_ref()
211                         .assert_crate_local()
212                         .lint_root;
213                     self.register_violations(
214                         &[UnsafetyViolation {
215                             source_info,
216                             description: Symbol::intern("borrow of packed field"),
217                             details: Symbol::intern(
218                                 "fields of packed structs might be misaligned: dereferencing a \
219                             misaligned pointer or even just creating a misaligned reference \
220                             is undefined behavior",
221                             ),
222                             kind: UnsafetyViolationKind::BorrowPacked(lint_root),
223                         }],
224                         &[],
225                     );
226                 }
227             }
228             let is_borrow_of_interior_mut = context.is_borrow()
229                 && !Place::ty_from(&place.base, proj_base, self.body, self.tcx).ty.is_freeze(
230                     self.tcx,
231                     self.param_env,
232                     self.source_info.span,
233                 );
234             // prevent
235             // * `&mut x.field`
236             // * `x.field = y;`
237             // * `&x.field` if `field`'s type has interior mutability
238             // because either of these would allow modifying the layout constrained field and
239             // insert values that violate the layout constraints.
240             if context.is_mutating_use() || is_borrow_of_interior_mut {
241                 self.check_mut_borrowing_layout_constrained_field(place, context.is_mutating_use());
242             }
243             let old_source_info = self.source_info;
244             if let (PlaceBase::Local(local), []) = (&place.base, proj_base) {
245                 let decl = &self.body.local_decls[*local];
246                 if decl.internal {
247                     // Internal locals are used in the `move_val_init` desugaring.
248                     // We want to check unsafety against the source info of the
249                     // desugaring, rather than the source info of the RHS.
250                     self.source_info = self.body.local_decls[*local].source_info;
251                 } else if let LocalInfo::StaticRef { def_id, .. } = decl.local_info {
252                     if self.tcx.is_mutable_static(def_id) {
253                         self.require_unsafe(
254                             "use of mutable static",
255                             "mutable statics can be mutated by multiple threads: aliasing \
256                         violations or data races will cause undefined behavior",
257                             UnsafetyViolationKind::General,
258                         );
259                         return;
260                     } else if self.tcx.is_foreign_item(def_id) {
261                         self.require_unsafe(
262                             "use of extern static",
263                             "extern statics are not controlled by the Rust type system: \
264                         invalid data, aliasing violations or data races will cause \
265                         undefined behavior",
266                             UnsafetyViolationKind::General,
267                         );
268                         return;
269                     }
270                 }
271             }
272             let base_ty = Place::ty_from(&place.base, proj_base, self.body, self.tcx).ty;
273             match base_ty.kind {
274                 ty::RawPtr(..) => self.require_unsafe(
275                     "dereference of raw pointer",
276                     "raw pointers may be NULL, dangling or unaligned; they can violate \
277                          aliasing rules and cause data races: all of these are undefined \
278                          behavior",
279                     UnsafetyViolationKind::General,
280                 ),
281                 ty::Adt(adt, _) => {
282                     if adt.is_union() {
283                         if context == PlaceContext::MutatingUse(MutatingUseContext::Store)
284                             || context == PlaceContext::MutatingUse(MutatingUseContext::Drop)
285                             || context == PlaceContext::MutatingUse(MutatingUseContext::AsmOutput)
286                         {
287                             let elem_ty = match elem {
288                                 ProjectionElem::Field(_, ty) => ty,
289                                 _ => span_bug!(
290                                     self.source_info.span,
291                                     "non-field projection {:?} from union?",
292                                     place
293                                 ),
294                             };
295                             if !elem_ty.is_copy_modulo_regions(
296                                 self.tcx,
297                                 self.param_env,
298                                 self.source_info.span,
299                             ) {
300                                 self.require_unsafe(
301                                     "assignment to non-`Copy` union field",
302                                     "the previous content of the field will be dropped, which \
303                                      causes undefined behavior if the field was not properly \
304                                      initialized",
305                                     UnsafetyViolationKind::GeneralAndConstFn,
306                                 )
307                             } else {
308                                 // write to non-move union, safe
309                             }
310                         } else {
311                             self.require_unsafe(
312                                 "access to union field",
313                                 "the field may not be properly initialized: using \
314                                  uninitialized data will cause undefined behavior",
315                                 UnsafetyViolationKind::GeneralAndConstFn,
316                             )
317                         }
318                     }
319                 }
320                 _ => {}
321             }
322             self.source_info = old_source_info;
323         }
324     }
325 }
326
327 impl<'a, 'tcx> UnsafetyChecker<'a, 'tcx> {
328     fn require_unsafe(
329         &mut self,
330         description: &'static str,
331         details: &'static str,
332         kind: UnsafetyViolationKind,
333     ) {
334         let source_info = self.source_info;
335         self.register_violations(
336             &[UnsafetyViolation {
337                 source_info,
338                 description: Symbol::intern(description),
339                 details: Symbol::intern(details),
340                 kind,
341             }],
342             &[],
343         );
344     }
345
346     fn register_violations(
347         &mut self,
348         violations: &[UnsafetyViolation],
349         unsafe_blocks: &[(hir::HirId, bool)],
350     ) {
351         let safety = self.body.source_scopes[self.source_info.scope]
352             .local_data
353             .as_ref()
354             .assert_crate_local()
355             .safety;
356         let within_unsafe = match safety {
357             // `unsafe` blocks are required in safe code
358             Safety::Safe => {
359                 for violation in violations {
360                     let mut violation = violation.clone();
361                     match violation.kind {
362                         UnsafetyViolationKind::GeneralAndConstFn
363                         | UnsafetyViolationKind::General => {}
364                         UnsafetyViolationKind::BorrowPacked(_) => {
365                             if self.min_const_fn {
366                                 // const fns don't need to be backwards compatible and can
367                                 // emit these violations as a hard error instead of a backwards
368                                 // compat lint
369                                 violation.kind = UnsafetyViolationKind::General;
370                             }
371                         }
372                     }
373                     if !self.violations.contains(&violation) {
374                         self.violations.push(violation)
375                     }
376                 }
377                 false
378             }
379             // `unsafe` function bodies allow unsafe without additional unsafe blocks
380             Safety::BuiltinUnsafe | Safety::FnUnsafe => true,
381             Safety::ExplicitUnsafe(hir_id) => {
382                 // mark unsafe block as used if there are any unsafe operations inside
383                 if !violations.is_empty() {
384                     self.used_unsafe.insert(hir_id);
385                 }
386                 // only some unsafety is allowed in const fn
387                 if self.min_const_fn {
388                     for violation in violations {
389                         match violation.kind {
390                             // these unsafe things are stable in const fn
391                             UnsafetyViolationKind::GeneralAndConstFn => {}
392                             // these things are forbidden in const fns
393                             UnsafetyViolationKind::General
394                             | UnsafetyViolationKind::BorrowPacked(_) => {
395                                 let mut violation = violation.clone();
396                                 // const fns don't need to be backwards compatible and can
397                                 // emit these violations as a hard error instead of a backwards
398                                 // compat lint
399                                 violation.kind = UnsafetyViolationKind::General;
400                                 if !self.violations.contains(&violation) {
401                                     self.violations.push(violation)
402                                 }
403                             }
404                         }
405                     }
406                 }
407                 true
408             }
409         };
410         self.inherited_blocks.extend(
411             unsafe_blocks.iter().map(|&(hir_id, is_used)| (hir_id, is_used && !within_unsafe)),
412         );
413     }
414     fn check_mut_borrowing_layout_constrained_field(
415         &mut self,
416         place: &Place<'tcx>,
417         is_mut_use: bool,
418     ) {
419         let mut cursor = place.projection.as_ref();
420         while let &[ref proj_base @ .., elem] = cursor {
421             cursor = proj_base;
422
423             match elem {
424                 ProjectionElem::Field(..) => {
425                     let ty =
426                         Place::ty_from(&place.base, proj_base, &self.body.local_decls, self.tcx).ty;
427                     match ty.kind {
428                         ty::Adt(def, _) => match self.tcx.layout_scalar_valid_range(def.did) {
429                             (Bound::Unbounded, Bound::Unbounded) => {}
430                             _ => {
431                                 let (description, details) = if is_mut_use {
432                                     (
433                                         "mutation of layout constrained field",
434                                         "mutating layout constrained fields cannot statically be \
435                                         checked for valid values",
436                                     )
437                                 } else {
438                                     (
439                                         "borrow of layout constrained field with interior \
440                                         mutability",
441                                         "references to fields of layout constrained fields \
442                                         lose the constraints. Coupled with interior mutability, \
443                                         the field can be changed to invalid values",
444                                     )
445                                 };
446                                 let source_info = self.source_info;
447                                 self.register_violations(
448                                     &[UnsafetyViolation {
449                                         source_info,
450                                         description: Symbol::intern(description),
451                                         details: Symbol::intern(details),
452                                         kind: UnsafetyViolationKind::GeneralAndConstFn,
453                                     }],
454                                     &[],
455                                 );
456                             }
457                         },
458                         _ => {}
459                     }
460                 }
461                 _ => {}
462             }
463         }
464     }
465 }
466
467 pub(crate) fn provide(providers: &mut Providers<'_>) {
468     *providers = Providers { unsafety_check_result, unsafe_derive_on_repr_packed, ..*providers };
469 }
470
471 struct UnusedUnsafeVisitor<'a> {
472     used_unsafe: &'a FxHashSet<hir::HirId>,
473     unsafe_blocks: &'a mut Vec<(hir::HirId, bool)>,
474 }
475
476 impl<'a, 'tcx> intravisit::Visitor<'tcx> for UnusedUnsafeVisitor<'a> {
477     fn nested_visit_map<'this>(&'this mut self) -> intravisit::NestedVisitorMap<'this, 'tcx> {
478         intravisit::NestedVisitorMap::None
479     }
480
481     fn visit_block(&mut self, block: &'tcx hir::Block<'tcx>) {
482         intravisit::walk_block(self, block);
483
484         if let hir::BlockCheckMode::UnsafeBlock(hir::UnsafeSource::UserProvided) = block.rules {
485             self.unsafe_blocks.push((block.hir_id, self.used_unsafe.contains(&block.hir_id)));
486         }
487     }
488 }
489
490 fn check_unused_unsafe(
491     tcx: TyCtxt<'_>,
492     def_id: DefId,
493     used_unsafe: &FxHashSet<hir::HirId>,
494     unsafe_blocks: &mut Vec<(hir::HirId, bool)>,
495 ) {
496     let body_id =
497         tcx.hir().as_local_hir_id(def_id).and_then(|hir_id| tcx.hir().maybe_body_owned_by(hir_id));
498
499     let body_id = match body_id {
500         Some(body) => body,
501         None => {
502             debug!("check_unused_unsafe({:?}) - no body found", def_id);
503             return;
504         }
505     };
506     let body = tcx.hir().body(body_id);
507     debug!("check_unused_unsafe({:?}, body={:?}, used_unsafe={:?})", def_id, body, used_unsafe);
508
509     let mut visitor = UnusedUnsafeVisitor { used_unsafe, unsafe_blocks };
510     intravisit::Visitor::visit_body(&mut visitor, body);
511 }
512
513 fn unsafety_check_result(tcx: TyCtxt<'_>, def_id: DefId) -> UnsafetyCheckResult {
514     debug!("unsafety_violations({:?})", def_id);
515
516     // N.B., this borrow is valid because all the consumers of
517     // `mir_built` force this.
518     let body = &tcx.mir_built(def_id).borrow();
519
520     let param_env = tcx.param_env(def_id);
521
522     let id = tcx.hir().as_local_hir_id(def_id).unwrap();
523     let (const_context, min_const_fn) = match tcx.hir().body_owner_kind(id) {
524         hir::BodyOwnerKind::Closure => (false, false),
525         hir::BodyOwnerKind::Fn => (tcx.is_const_fn(def_id), tcx.is_min_const_fn(def_id)),
526         hir::BodyOwnerKind::Const | hir::BodyOwnerKind::Static(_) => (true, false),
527     };
528     let mut checker = UnsafetyChecker::new(const_context, min_const_fn, body, tcx, param_env);
529     // mir_built ensures that body has a computed cache, so we don't (and can't) attempt to
530     // recompute it here.
531     let body = body.unwrap_read_only();
532     checker.visit_body(body);
533
534     check_unused_unsafe(tcx, def_id, &checker.used_unsafe, &mut checker.inherited_blocks);
535     UnsafetyCheckResult {
536         violations: checker.violations.into(),
537         unsafe_blocks: checker.inherited_blocks.into(),
538     }
539 }
540
541 fn unsafe_derive_on_repr_packed(tcx: TyCtxt<'_>, def_id: DefId) {
542     let lint_hir_id = tcx
543         .hir()
544         .as_local_hir_id(def_id)
545         .unwrap_or_else(|| bug!("checking unsafety for non-local def id {:?}", def_id));
546
547     // FIXME: when we make this a hard error, this should have its
548     // own error code.
549     let message = if tcx.generics_of(def_id).own_requires_monomorphization() {
550         "`#[derive]` can't be used on a `#[repr(packed)]` struct with \
551          type or const parameters (error E0133)"
552             .to_string()
553     } else {
554         "`#[derive]` can't be used on a `#[repr(packed)]` struct that \
555          does not derive Copy (error E0133)"
556             .to_string()
557     };
558     tcx.lint_hir(SAFE_PACKED_BORROWS, lint_hir_id, tcx.def_span(def_id), &message);
559 }
560
561 /// Returns the `HirId` for an enclosing scope that is also `unsafe`.
562 fn is_enclosed(
563     tcx: TyCtxt<'_>,
564     used_unsafe: &FxHashSet<hir::HirId>,
565     id: hir::HirId,
566 ) -> Option<(String, hir::HirId)> {
567     let parent_id = tcx.hir().get_parent_node(id);
568     if parent_id != id {
569         if used_unsafe.contains(&parent_id) {
570             Some(("block".to_string(), parent_id))
571         } else if let Some(Node::Item(&hir::Item {
572             kind: hir::ItemKind::Fn(ref sig, _, _), ..
573         })) = tcx.hir().find(parent_id)
574         {
575             match sig.header.unsafety {
576                 hir::Unsafety::Unsafe => Some(("fn".to_string(), parent_id)),
577                 hir::Unsafety::Normal => None,
578             }
579         } else {
580             is_enclosed(tcx, used_unsafe, parent_id)
581         }
582     } else {
583         None
584     }
585 }
586
587 fn report_unused_unsafe(tcx: TyCtxt<'_>, used_unsafe: &FxHashSet<hir::HirId>, id: hir::HirId) {
588     let span = tcx.sess.source_map().def_span(tcx.hir().span(id));
589     let msg = "unnecessary `unsafe` block";
590     let mut db = tcx.struct_span_lint_hir(UNUSED_UNSAFE, id, span, msg);
591     db.span_label(span, msg);
592     if let Some((kind, id)) = is_enclosed(tcx, used_unsafe, id) {
593         db.span_label(
594             tcx.sess.source_map().def_span(tcx.hir().span(id)),
595             format!("because it's nested under this `unsafe` {}", kind),
596         );
597     }
598     db.emit();
599 }
600
601 fn builtin_derive_def_id(tcx: TyCtxt<'_>, def_id: DefId) -> Option<DefId> {
602     debug!("builtin_derive_def_id({:?})", def_id);
603     if let Some(impl_def_id) = tcx.impl_of_method(def_id) {
604         if tcx.has_attr(impl_def_id, sym::automatically_derived) {
605             debug!("builtin_derive_def_id({:?}) - is {:?}", def_id, impl_def_id);
606             Some(impl_def_id)
607         } else {
608             debug!("builtin_derive_def_id({:?}) - not automatically derived", def_id);
609             None
610         }
611     } else {
612         debug!("builtin_derive_def_id({:?}) - not a method", def_id);
613         None
614     }
615 }
616
617 pub fn check_unsafety(tcx: TyCtxt<'_>, def_id: DefId) {
618     debug!("check_unsafety({:?})", def_id);
619
620     // closures are handled by their parent fn.
621     if tcx.is_closure(def_id) {
622         return;
623     }
624
625     let UnsafetyCheckResult { violations, unsafe_blocks } = tcx.unsafety_check_result(def_id);
626
627     for &UnsafetyViolation { source_info, description, details, kind } in violations.iter() {
628         // Report an error.
629         match kind {
630             UnsafetyViolationKind::GeneralAndConstFn | UnsafetyViolationKind::General => {
631                 struct_span_err!(
632                     tcx.sess,
633                     source_info.span,
634                     E0133,
635                     "{} is unsafe and requires unsafe function or block",
636                     description
637                 )
638                 .span_label(source_info.span, &*description.as_str())
639                 .note(&details.as_str())
640                 .emit();
641             }
642             UnsafetyViolationKind::BorrowPacked(lint_hir_id) => {
643                 if let Some(impl_def_id) = builtin_derive_def_id(tcx, def_id) {
644                     tcx.unsafe_derive_on_repr_packed(impl_def_id);
645                 } else {
646                     tcx.lint_node_note(
647                         SAFE_PACKED_BORROWS,
648                         lint_hir_id,
649                         source_info.span,
650                         &format!(
651                             "{} is unsafe and requires unsafe function or block \
652                                             (error E0133)",
653                             description
654                         ),
655                         &details.as_str(),
656                     );
657                 }
658             }
659         }
660     }
661
662     let mut unsafe_blocks: Vec<_> = unsafe_blocks.into_iter().collect();
663     unsafe_blocks.sort_by_cached_key(|(hir_id, _)| tcx.hir().hir_to_node_id(*hir_id));
664     let used_unsafe: FxHashSet<_> =
665         unsafe_blocks.iter().flat_map(|&&(id, used)| used.then_some(id)).collect();
666     for &(block_id, is_used) in unsafe_blocks {
667         if !is_used {
668             report_unused_unsafe(tcx, &used_unsafe, block_id);
669         }
670     }
671 }