frontend 0.4.0

rustc's frontend with no LLVM and no std: parsing through MIR, as a library
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
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
// `#![no_std]`: these arrive with the standard prelude and name no path, so a `std::`
// search cannot see them - and a `#[derive]` can use them without the name appearing
// in this file at all, which is why they are not trimmed by inspection.
use alloc::borrow::ToOwned;
use alloc::boxed::Box;
use alloc::format;
use alloc::string::{String, ToString};
use alloc::vec;
use alloc::vec::Vec;

use crate::rustc_errors::codes::*;
use crate::rustc_errors::{
    Applicability, Diag, DiagCtxtHandle, DiagSymbolList, Diagnostic, EmissionGuarantee, Level,
    Subdiagnostic, msg,
};
use crate::rustc_lint_defs::Lint;
use crate::rustc_lint_defs::builtin::{ARITHMETIC_OVERFLOW, UNCONDITIONAL_PANIC};
use rustc_macros::{Diagnostic, Subdiagnostic};
use crate::rustc_middle::mir::AssertKind;
use crate::rustc_middle::ty::{Ty, TyCtxt};
use crate::rustc_span::def_id::DefId;
use crate::rustc_span::{Ident, Span, Symbol};

#[derive(Diagnostic)]
#[diag("function cannot return without recursing")]
#[help("a `loop` may express intention better if this is on purpose")]
pub(crate) struct UnconditionalRecursion {
    #[label("cannot return without recursing")]
    pub(crate) span: Span,
    #[label("recursive call site")]
    pub(crate) call_sites: Vec<Span>,
}

#[derive(Diagnostic)]
#[diag("`{$callee}` is incompatible with `#[rustc_force_inline]`")]
#[note("incompatible due to: {$reason}")]
pub(crate) struct InvalidForceInline {
    #[primary_span]
    pub attr_span: Span,
    #[label("`{$callee}` defined here")]
    pub callee_span: Span,
    pub callee: String,
    pub reason: &'static str,
}

#[derive(Diagnostic)]
pub(crate) enum ConstMutate {
    #[diag("attempting to modify a `const` item")]
    #[note(
        "each usage of a `const` item creates a new temporary; the original `const` item will not be modified"
    )]
    Modify {
        #[note("`const` item defined here")]
        konst: Span,
    },
    #[diag("taking a mutable reference to a `const` item")]
    #[note("each usage of a `const` item creates a new temporary")]
    #[note("the mutable reference will refer to this temporary, not the original `const` item")]
    MutBorrow {
        #[note("mutable reference created due to call to this method")]
        method_call: Option<Span>,
        #[note("`const` item defined here")]
        konst: Span,
    },
}

#[derive(Diagnostic)]
#[diag("reference to field of packed {$ty_descr} is unaligned", code = E0793)]
#[note(
    "this {$ty_descr} is {$align ->
        [one] {\"\"}
        *[other] {\"at most \"}
    }{$align}-byte aligned, but the type of this field may require higher alignment"
)]
#[note(
    "creating a misaligned reference is undefined behavior (even if that reference is never dereferenced)"
)]
#[help(
    "copy the field contents to a local variable, or replace the reference with a raw pointer and use `read_unaligned`/`write_unaligned` (loads and stores via `*p` must be properly aligned even when using raw pointers)"
)]
pub(crate) struct UnalignedPackedRef {
    #[primary_span]
    pub span: Span,
    pub ty_descr: &'static str,
    pub align: u64,
}

#[derive(Diagnostic)]
#[diag("MIR pass `{$name}` is unknown and will be ignored")]
pub(crate) struct UnknownPassName<'a> {
    pub(crate) name: &'a str,
}

#[derive(Diagnostic)]
#[diag("valid MIR pass names are: {$valid_passes}")]
pub(crate) struct ValidPassNames<'a> {
    pub(crate) valid_passes: DiagSymbolList<&'a str>,
}

pub(crate) struct AssertLint<P> {
    pub span: Span,
    pub assert_kind: AssertKind<P>,
    pub lint_kind: AssertLintKind,
}

pub(crate) enum AssertLintKind {
    ArithmeticOverflow,
    UnconditionalPanic,
}

impl<'a, P: core::fmt::Debug> Diagnostic<'a, ()> for AssertLint<P> {
    fn into_diag(self, dcx: DiagCtxtHandle<'a>, level: Level) -> Diag<'a, ()> {
        let mut diag = Diag::new(
            dcx,
            level,
            match self.lint_kind {
                AssertLintKind::ArithmeticOverflow => {
                    msg!("this arithmetic operation will overflow")
                }
                AssertLintKind::UnconditionalPanic => {
                    msg!("this operation will panic at runtime")
                }
            },
        );
        diag.span_label(self.span, self.assert_kind.to_string());
        diag
    }
}

impl AssertLintKind {
    pub(crate) fn lint(&self) -> &'static Lint {
        match self {
            AssertLintKind::ArithmeticOverflow => ARITHMETIC_OVERFLOW,
            AssertLintKind::UnconditionalPanic => UNCONDITIONAL_PANIC,
        }
    }
}

#[derive(Diagnostic)]
#[diag("this operation will panic at runtime")]
pub(crate) struct ConstNIsZero {
    #[label("const parameter `{$const_param_name}` is zero")]
    pub const_param_span: Span,
    pub const_param_name: Symbol,
}

#[derive(Diagnostic)]
#[diag("call to inline assembly that may unwind")]
pub(crate) struct AsmUnwindCall {
    #[label("call to inline assembly that may unwind")]
    pub span: Span,
}

#[derive(Diagnostic)]
#[diag(
    "call to {$foreign ->
        [true] foreign function
        *[false] function pointer
    } with FFI-unwind ABI"
)]
pub(crate) struct FfiUnwindCall {
    #[label(
        "call to {$foreign ->
            [true] foreign function
            *[false] function pointer
        } with FFI-unwind ABI"
    )]
    pub span: Span,
    pub foreign: bool,
}

#[derive(Diagnostic)]
#[diag("taking a reference to a function item does not give a function pointer")]
pub(crate) struct FnItemRef {
    #[suggestion(
        "cast `{$ident}` to obtain a function pointer",
        code = "{sugg}",
        applicability = "unspecified"
    )]
    pub span: Span,
    pub sugg: String,
    pub ident: Ident,
}

#[derive(Diagnostic)]
#[diag("unreachable {$descr}")]
pub(crate) struct UnreachableDueToUninhabited<'desc, 'tcx> {
    pub descr: &'desc str,
    #[label("unreachable {$descr}")]
    pub expr: Span,
    #[label("any code following this expression is unreachable")]
    #[note("this expression has type `{$ty}`, which is uninhabited")]
    pub orig: Span,
    pub ty: Ty<'tcx>,
}

#[derive(Diagnostic)]
#[diag("value captured by `{$name}` is never read")]
#[help("did you mean to capture by reference instead?")]
pub(crate) struct UnusedCaptureMaybeCaptureRef {
    pub name: Symbol,
}

#[derive(Diagnostic)]
#[diag("variable `{$name}` is assigned to, but never used")]
#[note("consider using `_{$name}` instead")]
pub(crate) struct UnusedVarAssignedOnly {
    pub name: Symbol,
    #[subdiagnostic]
    pub typo: Option<PatternTypo>,
}

#[derive(Diagnostic)]
#[diag("value assigned to `{$name}` is never read")]
pub(crate) struct UnusedAssign {
    pub name: Symbol,
    #[subdiagnostic]
    pub overwrite: Option<UnusedAssignOverwrite>,
    #[subdiagnostic]
    pub suggestion: Option<UnusedAssignSuggestion>,
    #[help("maybe it is overwritten before being read?")]
    pub help: bool,
}

pub(crate) struct UnusedAssignOverwrite {
    pub assigned_span: Span,
    pub overwrite_span: Span,
    pub name: Symbol,
}

impl Subdiagnostic for UnusedAssignOverwrite {
    fn add_to_diag<G: EmissionGuarantee>(self, diag: &mut Diag<'_, G>) {
        diag.span_label(self.assigned_span, "this value is reassigned later and never used");
        diag.span_label(
            self.overwrite_span,
            format!("`{}` is overwritten here before the previous value is read", self.name),
        );
    }
}

#[derive(Subdiagnostic)]
#[multipart_suggestion(
    "you might have meant to mutate the pointed at value being passed in, instead of changing the reference in the local binding",
    applicability = "maybe-incorrect"
)]
pub(crate) struct UnusedAssignSuggestion {
    pub pre: &'static str,
    #[suggestion_part(code = "{pre}mut ")]
    pub ty_span: Option<Span>,
    #[suggestion_part(code = "")]
    pub ty_ref_span: Span,
    #[suggestion_part(code = "*")]
    pub pre_lhs_span: Span,
    #[suggestion_part(code = "")]
    pub rhs_borrow_span: Span,
}

#[derive(Diagnostic)]
#[diag("value passed to `{$name}` is never read")]
#[help("maybe it is overwritten before being read?")]
pub(crate) struct UnusedAssignPassed {
    pub name: Symbol,
}

#[derive(Diagnostic)]
#[diag("unused variable: `{$name}`")]
pub(crate) struct UnusedVariable {
    pub name: Symbol,
    #[subdiagnostic]
    pub string_interp: Vec<UnusedVariableStringInterp>,
    #[subdiagnostic]
    pub sugg: UnusedVariableSugg,
}

#[derive(Subdiagnostic)]
pub(crate) enum UnusedVariableSugg {
    #[multipart_suggestion("try ignoring the field", applicability = "machine-applicable")]
    TryIgnore {
        #[suggestion_part(code = "{name}: _")]
        shorthands: Vec<Span>,
        #[suggestion_part(code = "_")]
        non_shorthands: Vec<Span>,
        name: String,
    },

    #[multipart_suggestion(
        "if this is intentional, prefix it with an underscore",
        applicability = "machine-applicable"
    )]
    TryPrefix {
        #[suggestion_part(code = "_{name}")]
        spans: Vec<Span>,
        name: Symbol,
        #[subdiagnostic]
        typo: Option<PatternTypo>,
    },

    #[help("`{$name}` is captured in macro and introduced a unused variable")]
    NoSugg {
        #[primary_span]
        span: Span,
        name: Symbol,
    },
}

pub(crate) struct UnusedVariableStringInterp {
    pub lit: Span,
}

impl Subdiagnostic for UnusedVariableStringInterp {
    fn add_to_diag<G: EmissionGuarantee>(self, diag: &mut Diag<'_, G>) {
        diag.span_label(
            self.lit,
            msg!("you might have meant to use string interpolation in this string literal"),
        );
        diag.multipart_suggestion(
            msg!("string interpolation only works in `format!` invocations"),
            vec![
                (self.lit.shrink_to_lo(), String::from("format!(")),
                (self.lit.shrink_to_hi(), String::from(")")),
            ],
            Applicability::MachineApplicable,
        );
    }
}

#[derive(Subdiagnostic)]
#[multipart_suggestion(
    "you might have meant to pattern match on the similarly named {$kind} `{$item_name}`",
    style = "verbose",
    applicability = "maybe-incorrect"
)]
pub(crate) struct PatternTypo {
    #[suggestion_part(code = "{code}")]
    pub span: Span,
    pub code: String,
    pub item_name: Symbol,
    pub kind: &'static str,
}

pub(crate) struct MustNotSupend<'a, 'tcx> {
    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> Diagnostic<'a, ()> for MustNotSupend<'_, '_> {
    fn into_diag(self, dcx: DiagCtxtHandle<'a>, level: Level) -> Diag<'a, ()> {
        let mut diag = Diag::new(
            dcx,
            level,
            msg!("{$pre}`{$def_path}`{$post} held across a suspend point, but should not be"),
        );
        diag.span_label(self.yield_sp, msg!("the value is held across this suspend point"));
        if let Some(reason) = self.reason {
            diag.subdiagnostic(reason);
        }
        diag.span_help(self.src_sp, msg!("consider using a block (`{\"{ ... }\"}`) to shrink the value's scope, ending before the suspend point"));
        diag.arg("pre", self.pre);
        diag.arg("def_path", self.tcx.def_path_str(self.def_id));
        diag.arg("post", self.post);
        diag
    }
}

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

#[derive(Diagnostic)]
#[diag("`{$callee}` could not be inlined into `{$caller}` but is required to be inlined")]
#[note("could not be inlined due to: {$reason}")]
pub(crate) struct ForceInlineFailure {
    #[label("within `{$caller}`...")]
    pub caller_span: Span,
    #[label("`{$callee}` defined here")]
    pub callee_span: Span,
    #[label("annotation here")]
    pub attr_span: Span,
    #[primary_span]
    #[label("...`{$callee}` called here")]
    pub call_span: Span,
    pub callee: String,
    pub caller: String,
    pub reason: &'static str,
    #[subdiagnostic]
    pub justification: Option<ForceInlineJustification>,
}

#[derive(Subdiagnostic)]
#[note("`{$callee}` is required to be inlined to: {$sym}")]
pub(crate) struct ForceInlineJustification {
    pub sym: Symbol,
    pub callee: String,
}

#[derive(Diagnostic)]
#[diag("field `{$name}` cannot be mutated outside `{$restriction_path}`")]
pub(crate) struct MutOfRestrictedField {
    #[primary_span]
    pub mut_span: Span,
    #[label("field restricted here")]
    pub restriction_span: Span,
    pub name: Symbol,
    pub restriction_path: String,
}

#[derive(Diagnostic)]
#[diag(
    "`{$name}` cannot be constructed using a `{$descr}` expression outside `{$restriction_path}`"
)]
pub(crate) struct ConstructionOfTyWithMutRestrictedField {
    #[primary_span]
    pub construction_span: Span,
    #[label("field restricted here")]
    pub restriction_span: Span,
    pub name: Symbol,
    pub descr: &'static str,
    pub restriction_path: String,
}