rustc_session/
errors.rs

1use std::num::{NonZero, ParseIntError};
2
3use rustc_ast::token;
4use rustc_ast::util::literal::LitError;
5use rustc_errors::codes::*;
6use rustc_errors::{
7    Diag, DiagCtxtHandle, DiagMessage, Diagnostic, EmissionGuarantee, ErrorGuaranteed, Level,
8    MultiSpan,
9};
10use rustc_macros::{Diagnostic, LintDiagnostic, Subdiagnostic};
11use rustc_span::{Span, Symbol};
12use rustc_target::spec::{SplitDebuginfo, StackProtector, TargetTuple};
13
14use crate::config::CrateType;
15use crate::parse::ParseSess;
16
17#[derive(Diagnostic)]
18pub(crate) enum AppleDeploymentTarget {
19    #[diag(session_apple_deployment_target_invalid)]
20    Invalid { env_var: &'static str, error: ParseIntError },
21    #[diag(session_apple_deployment_target_too_low)]
22    TooLow { env_var: &'static str, version: String, os_min: String },
23}
24
25pub(crate) struct FeatureGateError {
26    pub(crate) span: MultiSpan,
27    pub(crate) explain: DiagMessage,
28}
29
30impl<'a, G: EmissionGuarantee> Diagnostic<'a, G> for FeatureGateError {
31    #[track_caller]
32    fn into_diag(self, dcx: DiagCtxtHandle<'a>, level: Level) -> Diag<'a, G> {
33        Diag::new(dcx, level, self.explain).with_span(self.span).with_code(E0658)
34    }
35}
36
37#[derive(Subdiagnostic)]
38#[note(session_feature_diagnostic_for_issue)]
39pub(crate) struct FeatureDiagnosticForIssue {
40    pub(crate) n: NonZero<u32>,
41}
42
43#[derive(Subdiagnostic)]
44#[note(session_feature_suggest_upgrade_compiler)]
45pub(crate) struct SuggestUpgradeCompiler {
46    date: &'static str,
47}
48
49impl SuggestUpgradeCompiler {
50    pub(crate) fn ui_testing() -> Self {
51        Self { date: "YYYY-MM-DD" }
52    }
53
54    pub(crate) fn new() -> Option<Self> {
55        let date = option_env!("CFG_VER_DATE")?;
56
57        Some(Self { date })
58    }
59}
60
61#[derive(Subdiagnostic)]
62#[help(session_feature_diagnostic_help)]
63pub(crate) struct FeatureDiagnosticHelp {
64    pub(crate) feature: Symbol,
65}
66
67#[derive(Subdiagnostic)]
68#[suggestion(
69    session_feature_diagnostic_suggestion,
70    applicability = "maybe-incorrect",
71    code = "#![feature({feature})]\n"
72)]
73pub struct FeatureDiagnosticSuggestion {
74    pub feature: Symbol,
75    #[primary_span]
76    pub span: Span,
77}
78
79#[derive(Subdiagnostic)]
80#[help(session_cli_feature_diagnostic_help)]
81pub(crate) struct CliFeatureDiagnosticHelp {
82    pub(crate) feature: Symbol,
83}
84
85#[derive(Diagnostic)]
86#[diag(session_must_be_name_of_associated_function)]
87pub struct MustBeNameOfAssociatedFunction {
88    #[primary_span]
89    pub span: Span,
90}
91
92#[derive(Diagnostic)]
93#[diag(session_not_circumvent_feature)]
94pub(crate) struct NotCircumventFeature;
95
96#[derive(Diagnostic)]
97#[diag(session_linker_plugin_lto_windows_not_supported)]
98pub(crate) struct LinkerPluginToWindowsNotSupported;
99
100#[derive(Diagnostic)]
101#[diag(session_profile_use_file_does_not_exist)]
102pub(crate) struct ProfileUseFileDoesNotExist<'a> {
103    pub(crate) path: &'a std::path::Path,
104}
105
106#[derive(Diagnostic)]
107#[diag(session_profile_sample_use_file_does_not_exist)]
108pub(crate) struct ProfileSampleUseFileDoesNotExist<'a> {
109    pub(crate) path: &'a std::path::Path,
110}
111
112#[derive(Diagnostic)]
113#[diag(session_target_requires_unwind_tables)]
114pub(crate) struct TargetRequiresUnwindTables;
115
116#[derive(Diagnostic)]
117#[diag(session_instrumentation_not_supported)]
118pub(crate) struct InstrumentationNotSupported {
119    pub(crate) us: String,
120}
121
122#[derive(Diagnostic)]
123#[diag(session_sanitizer_not_supported)]
124pub(crate) struct SanitizerNotSupported {
125    pub(crate) us: String,
126}
127
128#[derive(Diagnostic)]
129#[diag(session_sanitizers_not_supported)]
130pub(crate) struct SanitizersNotSupported {
131    pub(crate) us: String,
132}
133
134#[derive(Diagnostic)]
135#[diag(session_cannot_mix_and_match_sanitizers)]
136pub(crate) struct CannotMixAndMatchSanitizers {
137    pub(crate) first: String,
138    pub(crate) second: String,
139}
140
141#[derive(Diagnostic)]
142#[diag(session_cannot_enable_crt_static_linux)]
143pub(crate) struct CannotEnableCrtStaticLinux;
144
145#[derive(Diagnostic)]
146#[diag(session_sanitizer_cfi_requires_lto)]
147pub(crate) struct SanitizerCfiRequiresLto;
148
149#[derive(Diagnostic)]
150#[diag(session_sanitizer_cfi_requires_single_codegen_unit)]
151pub(crate) struct SanitizerCfiRequiresSingleCodegenUnit;
152
153#[derive(Diagnostic)]
154#[diag(session_sanitizer_cfi_canonical_jump_tables_requires_cfi)]
155pub(crate) struct SanitizerCfiCanonicalJumpTablesRequiresCfi;
156
157#[derive(Diagnostic)]
158#[diag(session_sanitizer_cfi_generalize_pointers_requires_cfi)]
159pub(crate) struct SanitizerCfiGeneralizePointersRequiresCfi;
160
161#[derive(Diagnostic)]
162#[diag(session_sanitizer_cfi_normalize_integers_requires_cfi)]
163pub(crate) struct SanitizerCfiNormalizeIntegersRequiresCfi;
164
165#[derive(Diagnostic)]
166#[diag(session_sanitizer_kcfi_arity_requires_kcfi)]
167pub(crate) struct SanitizerKcfiArityRequiresKcfi;
168
169#[derive(Diagnostic)]
170#[diag(session_sanitizer_kcfi_requires_panic_abort)]
171pub(crate) struct SanitizerKcfiRequiresPanicAbort;
172
173#[derive(Diagnostic)]
174#[diag(session_split_lto_unit_requires_lto)]
175pub(crate) struct SplitLtoUnitRequiresLto;
176
177#[derive(Diagnostic)]
178#[diag(session_unstable_virtual_function_elimination)]
179pub(crate) struct UnstableVirtualFunctionElimination;
180
181#[derive(Diagnostic)]
182#[diag(session_unsupported_dwarf_version)]
183#[help(session_unsupported_dwarf_version_help)]
184pub(crate) struct UnsupportedDwarfVersion {
185    pub(crate) dwarf_version: u32,
186}
187
188#[derive(Diagnostic)]
189#[diag(session_embed_source_insufficient_dwarf_version)]
190pub(crate) struct EmbedSourceInsufficientDwarfVersion {
191    pub(crate) dwarf_version: u32,
192}
193
194#[derive(Diagnostic)]
195#[diag(session_embed_source_requires_debug_info)]
196pub(crate) struct EmbedSourceRequiresDebugInfo;
197
198#[derive(Diagnostic)]
199#[diag(session_target_stack_protector_not_supported)]
200pub(crate) struct StackProtectorNotSupportedForTarget<'a> {
201    pub(crate) stack_protector: StackProtector,
202    pub(crate) target_triple: &'a TargetTuple,
203}
204
205#[derive(Diagnostic)]
206#[diag(session_target_small_data_threshold_not_supported)]
207pub(crate) struct SmallDataThresholdNotSupportedForTarget<'a> {
208    pub(crate) target_triple: &'a TargetTuple,
209}
210
211#[derive(Diagnostic)]
212#[diag(session_branch_protection_requires_aarch64)]
213pub(crate) struct BranchProtectionRequiresAArch64;
214
215#[derive(Diagnostic)]
216#[diag(session_split_debuginfo_unstable_platform)]
217pub(crate) struct SplitDebugInfoUnstablePlatform {
218    pub(crate) debuginfo: SplitDebuginfo,
219}
220
221#[derive(Diagnostic)]
222#[diag(session_file_is_not_writeable)]
223pub(crate) struct FileIsNotWriteable<'a> {
224    pub(crate) file: &'a std::path::Path,
225}
226
227#[derive(Diagnostic)]
228#[diag(session_file_write_fail)]
229pub(crate) struct FileWriteFail<'a> {
230    pub(crate) path: &'a std::path::Path,
231    pub(crate) err: String,
232}
233
234#[derive(Diagnostic)]
235#[diag(session_crate_name_empty)]
236pub(crate) struct CrateNameEmpty {
237    #[primary_span]
238    pub(crate) span: Option<Span>,
239}
240
241#[derive(Diagnostic)]
242#[diag(session_invalid_character_in_crate_name)]
243pub(crate) struct InvalidCharacterInCrateName {
244    #[primary_span]
245    pub(crate) span: Option<Span>,
246    pub(crate) character: char,
247    pub(crate) crate_name: Symbol,
248}
249
250#[derive(Subdiagnostic)]
251#[multipart_suggestion(session_expr_parentheses_needed, applicability = "machine-applicable")]
252pub struct ExprParenthesesNeeded {
253    #[suggestion_part(code = "(")]
254    left: Span,
255    #[suggestion_part(code = ")")]
256    right: Span,
257}
258
259impl ExprParenthesesNeeded {
260    pub fn surrounding(s: Span) -> Self {
261        ExprParenthesesNeeded { left: s.shrink_to_lo(), right: s.shrink_to_hi() }
262    }
263}
264
265#[derive(Diagnostic)]
266#[diag(session_skipping_const_checks)]
267pub(crate) struct SkippingConstChecks {
268    #[subdiagnostic]
269    pub(crate) unleashed_features: Vec<UnleashedFeatureHelp>,
270}
271
272#[derive(Subdiagnostic)]
273pub(crate) enum UnleashedFeatureHelp {
274    #[help(session_unleashed_feature_help_named)]
275    Named {
276        #[primary_span]
277        span: Span,
278        gate: Symbol,
279    },
280    #[help(session_unleashed_feature_help_unnamed)]
281    Unnamed {
282        #[primary_span]
283        span: Span,
284    },
285}
286
287#[derive(Diagnostic)]
288#[diag(session_invalid_literal_suffix)]
289struct InvalidLiteralSuffix<'a> {
290    #[primary_span]
291    #[label]
292    span: Span,
293    // FIXME(#100717)
294    kind: &'a str,
295    suffix: Symbol,
296}
297
298#[derive(Diagnostic)]
299#[diag(session_invalid_int_literal_width)]
300#[help]
301struct InvalidIntLiteralWidth {
302    #[primary_span]
303    span: Span,
304    width: String,
305}
306
307#[derive(Diagnostic)]
308#[diag(session_invalid_num_literal_base_prefix)]
309#[note]
310struct InvalidNumLiteralBasePrefix {
311    #[primary_span]
312    #[suggestion(applicability = "maybe-incorrect", code = "{fixed}")]
313    span: Span,
314    fixed: String,
315}
316
317#[derive(Diagnostic)]
318#[diag(session_invalid_num_literal_suffix)]
319#[help]
320struct InvalidNumLiteralSuffix {
321    #[primary_span]
322    #[label]
323    span: Span,
324    suffix: String,
325}
326
327#[derive(Diagnostic)]
328#[diag(session_invalid_float_literal_width)]
329#[help]
330struct InvalidFloatLiteralWidth {
331    #[primary_span]
332    span: Span,
333    width: String,
334}
335
336#[derive(Diagnostic)]
337#[diag(session_invalid_float_literal_suffix)]
338#[help]
339struct InvalidFloatLiteralSuffix {
340    #[primary_span]
341    #[label]
342    span: Span,
343    suffix: String,
344}
345
346#[derive(Diagnostic)]
347#[diag(session_int_literal_too_large)]
348#[note]
349struct IntLiteralTooLarge {
350    #[primary_span]
351    span: Span,
352    limit: String,
353}
354
355#[derive(Diagnostic)]
356#[diag(session_hexadecimal_float_literal_not_supported)]
357struct HexadecimalFloatLiteralNotSupported {
358    #[primary_span]
359    #[label(session_not_supported)]
360    span: Span,
361}
362
363#[derive(Diagnostic)]
364#[diag(session_octal_float_literal_not_supported)]
365struct OctalFloatLiteralNotSupported {
366    #[primary_span]
367    #[label(session_not_supported)]
368    span: Span,
369}
370
371#[derive(Diagnostic)]
372#[diag(session_binary_float_literal_not_supported)]
373struct BinaryFloatLiteralNotSupported {
374    #[primary_span]
375    #[label(session_not_supported)]
376    span: Span,
377}
378
379#[derive(Diagnostic)]
380#[diag(session_unsupported_crate_type_for_codegen_backend)]
381pub(crate) struct UnsupportedCrateTypeForCodegenBackend {
382    pub(crate) crate_type: CrateType,
383    pub(crate) codegen_backend: &'static str,
384}
385
386#[derive(Diagnostic)]
387#[diag(session_unsupported_crate_type_for_target)]
388pub(crate) struct UnsupportedCrateTypeForTarget<'a> {
389    pub(crate) crate_type: CrateType,
390    pub(crate) target_triple: &'a TargetTuple,
391}
392
393pub fn report_lit_error(
394    psess: &ParseSess,
395    err: LitError,
396    lit: token::Lit,
397    span: Span,
398) -> ErrorGuaranteed {
399    create_lit_error(psess, err, lit, span).emit()
400}
401
402pub fn create_lit_error(psess: &ParseSess, err: LitError, lit: token::Lit, span: Span) -> Diag<'_> {
403    // Checks if `s` looks like i32 or u1234 etc.
404    fn looks_like_width_suffix(first_chars: &[char], s: &str) -> bool {
405        s.len() > 1 && s.starts_with(first_chars) && s[1..].chars().all(|c| c.is_ascii_digit())
406    }
407
408    // Try to lowercase the prefix if the prefix and suffix are valid.
409    fn fix_base_capitalisation(prefix: &str, suffix: &str) -> Option<String> {
410        let mut chars = suffix.chars();
411
412        let base_char = chars.next().unwrap();
413        let base = match base_char {
414            'B' => 2,
415            'O' => 8,
416            'X' => 16,
417            _ => return None,
418        };
419
420        // check that the suffix contains only base-appropriate characters
421        let valid = prefix == "0"
422            && chars
423                .filter(|c| *c != '_')
424                .take_while(|c| *c != 'i' && *c != 'u')
425                .all(|c| c.to_digit(base).is_some());
426
427        valid.then(|| format!("0{}{}", base_char.to_ascii_lowercase(), &suffix[1..]))
428    }
429
430    let dcx = psess.dcx();
431    match err {
432        LitError::InvalidSuffix(suffix) => {
433            dcx.create_err(InvalidLiteralSuffix { span, kind: lit.kind.descr(), suffix })
434        }
435        LitError::InvalidIntSuffix(suffix) => {
436            let suf = suffix.as_str();
437            if looks_like_width_suffix(&['i', 'u'], suf) {
438                // If it looks like a width, try to be helpful.
439                dcx.create_err(InvalidIntLiteralWidth { span, width: suf[1..].into() })
440            } else if let Some(fixed) = fix_base_capitalisation(lit.symbol.as_str(), suf) {
441                dcx.create_err(InvalidNumLiteralBasePrefix { span, fixed })
442            } else {
443                dcx.create_err(InvalidNumLiteralSuffix { span, suffix: suf.to_string() })
444            }
445        }
446        LitError::InvalidFloatSuffix(suffix) => {
447            let suf = suffix.as_str();
448            if looks_like_width_suffix(&['f'], suf) {
449                // If it looks like a width, try to be helpful.
450                dcx.create_err(InvalidFloatLiteralWidth { span, width: suf[1..].to_string() })
451            } else {
452                dcx.create_err(InvalidFloatLiteralSuffix { span, suffix: suf.to_string() })
453            }
454        }
455        LitError::NonDecimalFloat(base) => match base {
456            16 => dcx.create_err(HexadecimalFloatLiteralNotSupported { span }),
457            8 => dcx.create_err(OctalFloatLiteralNotSupported { span }),
458            2 => dcx.create_err(BinaryFloatLiteralNotSupported { span }),
459            _ => unreachable!(),
460        },
461        LitError::IntTooLarge(base) => {
462            let max = u128::MAX;
463            let limit = match base {
464                2 => format!("{max:#b}"),
465                8 => format!("{max:#o}"),
466                16 => format!("{max:#x}"),
467                _ => format!("{max}"),
468            };
469            dcx.create_err(IntLiteralTooLarge { span, limit })
470        }
471    }
472}
473
474#[derive(Diagnostic)]
475#[diag(session_incompatible_linker_flavor)]
476#[note]
477pub(crate) struct IncompatibleLinkerFlavor {
478    pub(crate) flavor: &'static str,
479    pub(crate) compatible_list: String,
480}
481
482#[derive(Diagnostic)]
483#[diag(session_function_return_requires_x86_or_x86_64)]
484pub(crate) struct FunctionReturnRequiresX86OrX8664;
485
486#[derive(Diagnostic)]
487#[diag(session_function_return_thunk_extern_requires_non_large_code_model)]
488pub(crate) struct FunctionReturnThunkExternRequiresNonLargeCodeModel;
489
490#[derive(Diagnostic)]
491#[diag(session_indirect_branch_cs_prefix_requires_x86_or_x86_64)]
492pub(crate) struct IndirectBranchCsPrefixRequiresX86OrX8664;
493
494#[derive(Diagnostic)]
495#[diag(session_unsupported_regparm)]
496pub(crate) struct UnsupportedRegparm {
497    pub(crate) regparm: u32,
498}
499
500#[derive(Diagnostic)]
501#[diag(session_unsupported_regparm_arch)]
502pub(crate) struct UnsupportedRegparmArch;
503
504#[derive(Diagnostic)]
505#[diag(session_unsupported_reg_struct_return_arch)]
506pub(crate) struct UnsupportedRegStructReturnArch;
507
508#[derive(Diagnostic)]
509#[diag(session_failed_to_create_profiler)]
510pub(crate) struct FailedToCreateProfiler {
511    pub(crate) err: String,
512}
513
514#[derive(Diagnostic)]
515#[diag(session_soft_float_ignored)]
516#[note]
517pub(crate) struct SoftFloatIgnored;
518
519#[derive(Diagnostic)]
520#[diag(session_soft_float_deprecated)]
521#[note]
522#[note(session_soft_float_deprecated_issue)]
523pub(crate) struct SoftFloatDeprecated;
524
525#[derive(LintDiagnostic)]
526#[diag(session_unexpected_builtin_cfg)]
527#[note(session_controlled_by)]
528#[note(session_incoherent)]
529pub(crate) struct UnexpectedBuiltinCfg {
530    pub(crate) cfg: String,
531    pub(crate) cfg_name: Symbol,
532    pub(crate) controlled_by: &'static str,
533}