1 //! Unsafety checker: every impl either implements a trait defined in this
2 //! crate or pertains to a type defined in this crate.
4 use rustc_errors::struct_span_err;
6 use rustc_hir::Unsafety;
7 use rustc_middle::ty::TyCtxt;
8 use rustc_span::def_id::LocalDefId;
10 pub(super) fn check_item(tcx: TyCtxt<'_>, def_id: LocalDefId) {
11 let item = tcx.hir().expect_item(def_id);
12 let impl_ = item.expect_impl();
14 if let Some(trait_ref) = tcx.impl_trait_ref(item.owner_id) {
15 let trait_ref = trait_ref.subst_identity();
16 let trait_def = tcx.trait_def(trait_ref.def_id);
18 impl_.generics.params.iter().find(|p| p.pure_wrt_drop).map(|_| "may_dangle");
19 match (trait_def.unsafety, unsafe_attr, impl_.unsafety, impl_.polarity) {
20 (Unsafety::Normal, None, Unsafety::Unsafe, hir::ImplPolarity::Positive) => {
25 "implementing the trait `{}` is not unsafe",
26 trait_ref.print_only_trait_path()
28 .span_suggestion_verbose(
29 item.span.with_hi(item.span.lo() + rustc_span::BytePos(7)),
30 "remove `unsafe` from this trait implementation",
32 rustc_errors::Applicability::MachineApplicable,
37 (Unsafety::Unsafe, _, Unsafety::Normal, hir::ImplPolarity::Positive) => {
42 "the trait `{}` requires an `unsafe impl` declaration",
43 trait_ref.print_only_trait_path()
46 "the trait `{}` enforces invariants that the compiler can't check. \
47 Review the trait documentation and make sure this implementation \
48 upholds those invariants before adding the `unsafe` keyword",
49 trait_ref.print_only_trait_path()
51 .span_suggestion_verbose(
52 item.span.shrink_to_lo(),
53 "add `unsafe` to this trait implementation",
55 rustc_errors::Applicability::MaybeIncorrect,
60 (Unsafety::Normal, Some(attr_name), Unsafety::Normal, hir::ImplPolarity::Positive) => {
65 "requires an `unsafe impl` declaration due to `#[{}]` attribute",
69 "the trait `{}` enforces invariants that the compiler can't check. \
70 Review the trait documentation and make sure this implementation \
71 upholds those invariants before adding the `unsafe` keyword",
72 trait_ref.print_only_trait_path()
74 .span_suggestion_verbose(
75 item.span.shrink_to_lo(),
76 "add `unsafe` to this trait implementation",
78 rustc_errors::Applicability::MaybeIncorrect,
83 (_, _, Unsafety::Unsafe, hir::ImplPolarity::Negative(_)) => {
84 // Reported in AST validation
85 tcx.sess.delay_span_bug(item.span, "unsafe negative impl");
87 (_, _, Unsafety::Normal, hir::ImplPolarity::Negative(_))
88 | (Unsafety::Unsafe, _, Unsafety::Unsafe, hir::ImplPolarity::Positive)
89 | (Unsafety::Normal, Some(_), Unsafety::Unsafe, hir::ImplPolarity::Positive)
90 | (Unsafety::Normal, None, Unsafety::Normal, _) => {