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