1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
use rustc_errors::{
    Applicability, DecorateLint, DiagnosticBuilder, DiagnosticMessage, EmissionGuarantee, Handler,
    IntoDiagnostic,
};
use rustc_macros::{Diagnostic, LintDiagnostic, Subdiagnostic};
use rustc_middle::mir::{AssertKind, UnsafetyViolationDetails};
use rustc_middle::ty::TyCtxt;
use rustc_session::lint::{self, Lint};
use rustc_span::def_id::DefId;
use rustc_span::Span;

#[derive(LintDiagnostic)]
pub(crate) enum ConstMutate {
    #[diag(mir_transform_const_modify)]
    #[note]
    Modify {
        #[note(mir_transform_const_defined_here)]
        konst: Span,
    },
    #[diag(mir_transform_const_mut_borrow)]
    #[note]
    #[note(mir_transform_note2)]
    MutBorrow {
        #[note(mir_transform_note3)]
        method_call: Option<Span>,
        #[note(mir_transform_const_defined_here)]
        konst: Span,
    },
}

#[derive(Diagnostic)]
#[diag(mir_transform_unaligned_packed_ref, code = "E0793")]
#[note]
#[note(mir_transform_note_ub)]
#[help]
pub(crate) struct UnalignedPackedRef {
    #[primary_span]
    pub span: Span,
}

#[derive(LintDiagnostic)]
#[diag(mir_transform_unused_unsafe)]
pub(crate) struct UnusedUnsafe {
    #[label(mir_transform_unused_unsafe)]
    pub span: Span,
    #[label]
    pub nested_parent: Option<Span>,
}

pub(crate) struct RequiresUnsafe {
    pub span: Span,
    pub details: RequiresUnsafeDetail,
    pub enclosing: Option<Span>,
    pub op_in_unsafe_fn_allowed: bool,
}

// The primary message for this diagnostic should be '{$label} is unsafe and...',
// so we need to eagerly translate the label here, which isn't supported by the derive API
// We could also exhaustively list out the primary messages for all unsafe violations,
// but this would result in a lot of duplication.
impl<'sess, G: EmissionGuarantee> IntoDiagnostic<'sess, G> for RequiresUnsafe {
    #[track_caller]
    fn into_diagnostic(self, handler: &'sess Handler) -> DiagnosticBuilder<'sess, G> {
        let mut diag =
            handler.struct_diagnostic(crate::fluent_generated::mir_transform_requires_unsafe);
        diag.code(rustc_errors::DiagnosticId::Error("E0133".to_string()));
        diag.set_span(self.span);
        diag.span_label(self.span, self.details.label());
        diag.note(self.details.note());
        let desc = handler.eagerly_translate_to_string(self.details.label(), [].into_iter());
        diag.set_arg("details", desc);
        diag.set_arg("op_in_unsafe_fn_allowed", self.op_in_unsafe_fn_allowed);
        if let Some(sp) = self.enclosing {
            diag.span_label(sp, crate::fluent_generated::mir_transform_not_inherited);
        }
        diag
    }
}

#[derive(Copy, Clone)]
pub(crate) struct RequiresUnsafeDetail {
    pub span: Span,
    pub violation: UnsafetyViolationDetails,
}

impl RequiresUnsafeDetail {
    fn note(self) -> DiagnosticMessage {
        use UnsafetyViolationDetails::*;
        match self.violation {
            CallToUnsafeFunction => crate::fluent_generated::mir_transform_call_to_unsafe_note,
            UseOfInlineAssembly => crate::fluent_generated::mir_transform_use_of_asm_note,
            InitializingTypeWith => {
                crate::fluent_generated::mir_transform_initializing_valid_range_note
            }
            CastOfPointerToInt => crate::fluent_generated::mir_transform_const_ptr2int_note,
            UseOfMutableStatic => crate::fluent_generated::mir_transform_use_of_static_mut_note,
            UseOfExternStatic => crate::fluent_generated::mir_transform_use_of_extern_static_note,
            DerefOfRawPointer => crate::fluent_generated::mir_transform_deref_ptr_note,
            AccessToUnionField => crate::fluent_generated::mir_transform_union_access_note,
            MutationOfLayoutConstrainedField => {
                crate::fluent_generated::mir_transform_mutation_layout_constrained_note
            }
            BorrowOfLayoutConstrainedField => {
                crate::fluent_generated::mir_transform_mutation_layout_constrained_borrow_note
            }
            CallToFunctionWith => crate::fluent_generated::mir_transform_target_feature_call_note,
        }
    }

    fn label(self) -> DiagnosticMessage {
        use UnsafetyViolationDetails::*;
        match self.violation {
            CallToUnsafeFunction => crate::fluent_generated::mir_transform_call_to_unsafe_label,
            UseOfInlineAssembly => crate::fluent_generated::mir_transform_use_of_asm_label,
            InitializingTypeWith => {
                crate::fluent_generated::mir_transform_initializing_valid_range_label
            }
            CastOfPointerToInt => crate::fluent_generated::mir_transform_const_ptr2int_label,
            UseOfMutableStatic => crate::fluent_generated::mir_transform_use_of_static_mut_label,
            UseOfExternStatic => crate::fluent_generated::mir_transform_use_of_extern_static_label,
            DerefOfRawPointer => crate::fluent_generated::mir_transform_deref_ptr_label,
            AccessToUnionField => crate::fluent_generated::mir_transform_union_access_label,
            MutationOfLayoutConstrainedField => {
                crate::fluent_generated::mir_transform_mutation_layout_constrained_label
            }
            BorrowOfLayoutConstrainedField => {
                crate::fluent_generated::mir_transform_mutation_layout_constrained_borrow_label
            }
            CallToFunctionWith => crate::fluent_generated::mir_transform_target_feature_call_label,
        }
    }
}

pub(crate) struct UnsafeOpInUnsafeFn {
    pub details: RequiresUnsafeDetail,

    /// These spans point to:
    ///  1. the start of the function body
    ///  2. the end of the function body
    ///  3. the function signature
    pub suggest_unsafe_block: Option<(Span, Span, Span)>,
}

impl<'a> DecorateLint<'a, ()> for UnsafeOpInUnsafeFn {
    #[track_caller]
    fn decorate_lint<'b>(
        self,
        diag: &'b mut DiagnosticBuilder<'a, ()>,
    ) -> &'b mut DiagnosticBuilder<'a, ()> {
        let handler = diag.handler().expect("lint should not yet be emitted");
        let desc = handler.eagerly_translate_to_string(self.details.label(), [].into_iter());
        diag.set_arg("details", desc);
        diag.span_label(self.details.span, self.details.label());
        diag.note(self.details.note());

        if let Some((start, end, fn_sig)) = self.suggest_unsafe_block {
            diag.span_note(fn_sig, crate::fluent_generated::mir_transform_note);
            diag.tool_only_multipart_suggestion(
                crate::fluent_generated::mir_transform_suggestion,
                vec![(start, " unsafe {".into()), (end, "}".into())],
                Applicability::MaybeIncorrect,
            );
        }

        diag
    }

    fn msg(&self) -> DiagnosticMessage {
        crate::fluent_generated::mir_transform_unsafe_op_in_unsafe_fn
    }
}

pub(crate) enum AssertLint<P> {
    ArithmeticOverflow(Span, AssertKind<P>),
    UnconditionalPanic(Span, AssertKind<P>),
}

impl<'a, P: std::fmt::Debug> DecorateLint<'a, ()> for AssertLint<P> {
    fn decorate_lint<'b>(
        self,
        diag: &'b mut DiagnosticBuilder<'a, ()>,
    ) -> &'b mut DiagnosticBuilder<'a, ()> {
        let span = self.span();
        let assert_kind = self.panic();
        let message = assert_kind.diagnostic_message();
        assert_kind.add_args(&mut |name, value| {
            diag.set_arg(name, value);
        });
        diag.span_label(span, message);

        diag
    }

    fn msg(&self) -> DiagnosticMessage {
        match self {
            AssertLint::ArithmeticOverflow(..) => {
                crate::fluent_generated::mir_transform_arithmetic_overflow
            }
            AssertLint::UnconditionalPanic(..) => {
                crate::fluent_generated::mir_transform_operation_will_panic
            }
        }
    }
}

impl<P> AssertLint<P> {
    pub fn lint(&self) -> &'static Lint {
        match self {
            AssertLint::ArithmeticOverflow(..) => lint::builtin::ARITHMETIC_OVERFLOW,
            AssertLint::UnconditionalPanic(..) => lint::builtin::UNCONDITIONAL_PANIC,
        }
    }
    pub fn span(&self) -> Span {
        match self {
            AssertLint::ArithmeticOverflow(sp, _) | AssertLint::UnconditionalPanic(sp, _) => *sp,
        }
    }
    pub fn panic(self) -> AssertKind<P> {
        match self {
            AssertLint::ArithmeticOverflow(_, p) | AssertLint::UnconditionalPanic(_, p) => p,
        }
    }
}

#[derive(LintDiagnostic)]
#[diag(mir_transform_ffi_unwind_call)]
pub(crate) struct FfiUnwindCall {
    #[label(mir_transform_ffi_unwind_call)]
    pub span: Span,
    pub foreign: bool,
}

#[derive(LintDiagnostic)]
#[diag(mir_transform_fn_item_ref)]
pub(crate) struct FnItemRef {
    #[suggestion(code = "{sugg}", applicability = "unspecified")]
    pub span: Span,
    pub sugg: String,
    pub ident: String,
}

pub(crate) struct MustNotSupend<'tcx, 'a> {
    pub tcx: TyCtxt<'tcx>,
    pub yield_sp: Span,
    pub reason: Option<MustNotSuspendReason>,
    pub src_sp: Span,
    pub pre: &'a str,
    pub def_id: DefId,
    pub post: &'a str,
}

// Needed for def_path_str
impl<'a> DecorateLint<'a, ()> for MustNotSupend<'_, '_> {
    fn decorate_lint<'b>(
        self,
        diag: &'b mut rustc_errors::DiagnosticBuilder<'a, ()>,
    ) -> &'b mut rustc_errors::DiagnosticBuilder<'a, ()> {
        diag.span_label(self.yield_sp, crate::fluent_generated::_subdiag::label);
        if let Some(reason) = self.reason {
            diag.subdiagnostic(reason);
        }
        diag.span_help(self.src_sp, crate::fluent_generated::_subdiag::help);
        diag.set_arg("pre", self.pre);
        diag.set_arg("def_path", self.tcx.def_path_str(self.def_id));
        diag.set_arg("post", self.post);
        diag
    }

    fn msg(&self) -> rustc_errors::DiagnosticMessage {
        crate::fluent_generated::mir_transform_must_not_suspend
    }
}

#[derive(Subdiagnostic)]
#[note(mir_transform_note)]
pub(crate) struct MustNotSuspendReason {
    #[primary_span]
    pub span: Span,
    pub reason: String,
}