diff --git a/Cargo.lock b/Cargo.lock index 85d3fc1aa7bf7..9c98946c9d390 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -3490,7 +3490,6 @@ dependencies = [ "rustc_data_structures", "rustc_errors", "rustc_feature", - "rustc_fluent_macro", "rustc_hir", "rustc_index", "rustc_macros", @@ -3672,7 +3671,6 @@ dependencies = [ "rustc_attr_parsing", "rustc_data_structures", "rustc_errors", - "rustc_fluent_macro", "rustc_fs_util", "rustc_hashes", "rustc_hir", @@ -3774,7 +3772,6 @@ dependencies = [ "libc", "rustc_abi", "rustc_ast", - "rustc_ast_lowering", "rustc_ast_passes", "rustc_ast_pretty", "rustc_borrowck", @@ -3787,7 +3784,6 @@ dependencies = [ "rustc_feature", "rustc_hir_analysis", "rustc_hir_pretty", - "rustc_hir_typeck", "rustc_index", "rustc_interface", "rustc_lexer", @@ -3875,7 +3871,6 @@ dependencies = [ "rustc_data_structures", "rustc_errors", "rustc_feature", - "rustc_fluent_macro", "rustc_hir", "rustc_lexer", "rustc_lint_defs", @@ -4017,7 +4012,6 @@ dependencies = [ "rustc_ast", "rustc_data_structures", "rustc_errors", - "rustc_fluent_macro", "rustc_hir", "rustc_hir_analysis", "rustc_hir_pretty", @@ -4039,7 +4033,6 @@ name = "rustc_incremental" version = "0.0.0" dependencies = [ "rand 0.9.2", - "rustc_ast", "rustc_data_structures", "rustc_errors", "rustc_fs_util", @@ -4051,7 +4044,6 @@ dependencies = [ "rustc_serialize", "rustc_session", "rustc_span", - "thin-vec", "tracing", ] @@ -4237,7 +4229,6 @@ dependencies = [ "rustc_errors", "rustc_expand", "rustc_feature", - "rustc_fluent_macro", "rustc_fs_util", "rustc_hir", "rustc_hir_pretty", @@ -4347,7 +4338,6 @@ dependencies = [ "rustc_const_eval", "rustc_data_structures", "rustc_errors", - "rustc_fluent_macro", "rustc_hir", "rustc_index", "rustc_infer", @@ -4534,9 +4524,11 @@ version = "0.0.0" dependencies = [ "measureme", "rustc_data_structures", + "rustc_errors", "rustc_hashes", "rustc_hir", "rustc_index", + "rustc_macros", "rustc_middle", "rustc_query_system", "rustc_serialize", @@ -4581,7 +4573,6 @@ dependencies = [ "rustc_errors", "rustc_expand", "rustc_feature", - "rustc_fluent_macro", "rustc_hir", "rustc_index", "rustc_macros", diff --git a/compiler/rustc/src/main.rs b/compiler/rustc/src/main.rs index 89c61cdf00a59..30d64b05cfde9 100644 --- a/compiler/rustc/src/main.rs +++ b/compiler/rustc/src/main.rs @@ -3,6 +3,8 @@ // Several crates are depended upon but unused so that they are present in the sysroot #![expect(unused_crate_dependencies)] +use std::process::ExitCode; + // A note about jemalloc: rustc uses jemalloc when built for CI and // distribution. The obvious way to do this is with the `#[global_allocator]` // mechanism. However, for complicated reasons (see @@ -38,6 +40,6 @@ #[cfg(feature = "jemalloc")] use tikv_jemalloc_sys as _; -fn main() { +fn main() -> ExitCode { rustc_driver::main() } diff --git a/compiler/rustc_ast_lowering/Cargo.toml b/compiler/rustc_ast_lowering/Cargo.toml index 6ac258155fe94..c00bac5d3c5a5 100644 --- a/compiler/rustc_ast_lowering/Cargo.toml +++ b/compiler/rustc_ast_lowering/Cargo.toml @@ -15,7 +15,6 @@ rustc_attr_parsing = { path = "../rustc_attr_parsing" } rustc_data_structures = { path = "../rustc_data_structures" } rustc_errors = { path = "../rustc_errors" } rustc_feature = { path = "../rustc_feature" } -rustc_fluent_macro = { path = "../rustc_fluent_macro" } rustc_hir = { path = "../rustc_hir" } rustc_index = { path = "../rustc_index" } rustc_macros = { path = "../rustc_macros" } diff --git a/compiler/rustc_ast_lowering/messages.ftl b/compiler/rustc_ast_lowering/messages.ftl deleted file mode 100644 index 0cd5c4f303dee..0000000000000 --- a/compiler/rustc_ast_lowering/messages.ftl +++ /dev/null @@ -1,191 +0,0 @@ -ast_lowering_abi_specified_multiple_times = - `{$prev_name}` ABI specified multiple times - .label = previously specified here - .note = these ABIs are equivalent on the current target - -ast_lowering_arbitrary_expression_in_pattern = - arbitrary expressions aren't allowed in patterns - .pattern_from_macro_note = the `expr` fragment specifier forces the metavariable's content to be an expression - .const_block_in_pattern_help = use a named `const`-item or an `if`-guard (`x if x == const {"{ ... }"}`) instead - -ast_lowering_argument = argument - -ast_lowering_assoc_ty_binding_in_dyn = - associated type bounds are not allowed in `dyn` types - .suggestion = use `impl Trait` to introduce a type instead - -ast_lowering_assoc_ty_parentheses = - parenthesized generic arguments cannot be used in associated type constraints - -ast_lowering_async_bound_not_on_trait = - `async` bound modifier only allowed on trait, not `{$descr}` - -ast_lowering_async_bound_only_for_fn_traits = - `async` bound modifier only allowed on `Fn`/`FnMut`/`FnOnce` traits - -ast_lowering_async_coroutines_not_supported = - `async` coroutines are not yet supported - -ast_lowering_att_syntax_only_x86 = - the `att_syntax` option is only supported on x86 - -ast_lowering_await_only_in_async_fn_and_blocks = - `await` is only allowed inside `async` functions and blocks - .label = only allowed inside `async` functions and blocks - -ast_lowering_bad_return_type_notation_inputs = - argument types not allowed with return type notation - .suggestion = remove the input types - -ast_lowering_bad_return_type_notation_needs_dots = return type notation arguments must be elided with `..` - .suggestion = use the correct syntax by adding `..` to the arguments - -ast_lowering_bad_return_type_notation_output = - return type not allowed with return type notation -ast_lowering_bad_return_type_notation_output_suggestion = use the right argument notation and remove the return type - -ast_lowering_bad_return_type_notation_position = return type notation not allowed in this position yet - -ast_lowering_clobber_abi_not_supported = - `clobber_abi` is not supported on this target - -ast_lowering_closure_cannot_be_static = closures cannot be static - -ast_lowering_coroutine_too_many_parameters = - too many parameters for a coroutine (expected 0 or 1 parameters) - -ast_lowering_default_field_in_tuple = default fields are not supported in tuple structs - .label = default fields are only supported on structs - -ast_lowering_delegation_cycle_in_signature_resolution = encountered a cycle during delegation signature resolution -ast_lowering_delegation_unresolved_callee = failed to resolve delegation callee -ast_lowering_does_not_support_modifiers = - the `{$class_name}` register class does not support template modifiers - -ast_lowering_extra_double_dot = - `..` can only be used once per {$ctx} pattern - .label = can only be used once per {$ctx} pattern - -ast_lowering_functional_record_update_destructuring_assignment = - functional record updates are not allowed in destructuring assignments - .suggestion = consider removing the trailing pattern - -ast_lowering_generic_param_default_in_binder = - defaults for generic parameters are not allowed in `for<...>` binders - -ast_lowering_generic_type_with_parentheses = - parenthesized type parameters may only be used with a `Fn` trait - .label = only `Fn` traits may use parentheses - -ast_lowering_inclusive_range_with_no_end = inclusive range with no end - -ast_lowering_inline_asm_unsupported_target = - inline assembly is unsupported on this target - -ast_lowering_invalid_abi = - invalid ABI: found `{$abi}` - .label = invalid ABI - .note = invoke `{$command}` for a full list of supported calling conventions - -ast_lowering_invalid_abi_clobber_abi = - invalid ABI for `clobber_abi` - .note = the following ABIs are supported on this target: {$supported_abis} - -ast_lowering_invalid_abi_suggestion = there's a similarly named valid ABI `{$suggestion}` - -ast_lowering_invalid_asm_template_modifier_const = - asm template modifiers are not allowed for `const` arguments - -ast_lowering_invalid_asm_template_modifier_label = - asm template modifiers are not allowed for `label` arguments - -ast_lowering_invalid_asm_template_modifier_reg_class = - invalid asm template modifier for this register class - -ast_lowering_invalid_asm_template_modifier_sym = - asm template modifiers are not allowed for `sym` arguments - -ast_lowering_invalid_legacy_const_generic_arg = - invalid argument to a legacy const generic: cannot have const blocks, closures, async blocks or items - -ast_lowering_invalid_legacy_const_generic_arg_suggestion = - try using a const generic argument instead - -ast_lowering_invalid_register = - invalid register `{$reg}`: {$error} - -ast_lowering_invalid_register_class = - invalid register class `{$reg_class}`: unknown register class - .note = the following register classes are supported on this target: {$supported_register_classes} - -ast_lowering_match_arm_with_no_body = - `match` arm with no body - .suggestion = add a body after the pattern - -ast_lowering_misplaced_double_dot = - `..` patterns are not allowed here - .note = only allowed in tuple, tuple struct, and slice patterns - -ast_lowering_misplaced_impl_trait = - `impl Trait` is not allowed in {$position} - .note = `impl Trait` is only allowed in arguments and return types of functions and methods - -ast_lowering_never_pattern_with_body = - a never pattern is always unreachable - .label = this will never be executed - .suggestion = remove this expression - -ast_lowering_never_pattern_with_guard = - a guard on a never pattern will never be run - .suggestion = remove this guard - -ast_lowering_no_precise_captures_on_apit = `use<...>` precise capturing syntax not allowed in argument-position `impl Trait` - -ast_lowering_previously_used_here = previously used here - -ast_lowering_register1 = register `{$reg1_name}` - -ast_lowering_register2 = register `{$reg2_name}` - -ast_lowering_register_class_only_clobber = - register class `{$reg_class_name}` can only be used as a clobber, not as an input or output -ast_lowering_register_class_only_clobber_stable = - register class `{$reg_class_name}` can only be used as a clobber in stable - -ast_lowering_register_conflict = - register `{$reg1_name}` conflicts with register `{$reg2_name}` - .help = use `lateout` instead of `out` to avoid conflict - -ast_lowering_remove_parentheses = remove these parentheses - -ast_lowering_sub_tuple_binding = - `{$ident_name} @` is not allowed in a {$ctx} - .label = this is only allowed in slice patterns - .help = remove this and bind each tuple field independently - -ast_lowering_sub_tuple_binding_suggestion = if you don't need to use the contents of {$ident}, discard the tuple's remaining fields - -ast_lowering_support_modifiers = - the `{$class_name}` register class supports the following template modifiers: {$modifiers} - -ast_lowering_template_modifier = template modifier - -ast_lowering_this_not_async = this is not `async` - -ast_lowering_underscore_expr_lhs_assign = - in expressions, `_` can only be used on the left-hand side of an assignment - .label = `_` not allowed here - -ast_lowering_union_default_field_values = unions cannot have default field values - -ast_lowering_unstable_inline_assembly = inline assembly is not stable yet on this architecture -ast_lowering_unstable_inline_assembly_label_operand_with_outputs = - using both label and output operands for inline assembly is unstable -ast_lowering_unstable_may_unwind = the `may_unwind` option is unstable - -ast_lowering_use_angle_brackets = use angle brackets instead - -ast_lowering_yield = yield syntax is experimental -ast_lowering_yield_in_closure = - `yield` can only be used in `#[coroutine]` closures, or `gen` blocks - .suggestion = use `#[coroutine]` to make this closure a coroutine diff --git a/compiler/rustc_ast_lowering/src/asm.rs b/compiler/rustc_ast_lowering/src/asm.rs index 36fcd4b924c88..fc1f198e8b2ab 100644 --- a/compiler/rustc_ast_lowering/src/asm.rs +++ b/compiler/rustc_ast_lowering/src/asm.rs @@ -3,6 +3,7 @@ use std::fmt::Write; use rustc_ast::*; use rustc_data_structures::fx::{FxHashMap, FxHashSet, FxIndexMap}; +use rustc_errors::inline_fluent; use rustc_hir as hir; use rustc_hir::def::{DefKind, Res}; use rustc_session::parse::feature_err; @@ -19,8 +20,7 @@ use super::errors::{ RegisterConflict, }; use crate::{ - AllowReturnTypeNotation, ImplTraitContext, ImplTraitPosition, ParamMode, - ResolverAstLoweringExt, fluent_generated as fluent, + AllowReturnTypeNotation, ImplTraitContext, ImplTraitPosition, ParamMode, ResolverAstLoweringExt, }; impl<'a, 'hir> LoweringContext<'a, 'hir> { @@ -67,7 +67,7 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> { &self.tcx.sess, sym::asm_experimental_arch, sp, - fluent::ast_lowering_unstable_inline_assembly, + inline_fluent!("inline assembly is not stable yet on this architecture"), ) .emit(); } @@ -84,7 +84,7 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> { &self.tcx.sess, sym::asm_unwind, sp, - fluent::ast_lowering_unstable_may_unwind, + inline_fluent!("the `may_unwind` option is unstable"), ) .emit(); } @@ -499,7 +499,9 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> { sess, sym::asm_goto_with_outputs, *op_sp, - fluent::ast_lowering_unstable_inline_assembly_label_operand_with_outputs, + inline_fluent!( + "using both label and output operands for inline assembly is unstable" + ), ) .emit(); } diff --git a/compiler/rustc_ast_lowering/src/errors.rs b/compiler/rustc_ast_lowering/src/errors.rs index 88e69e67d8a55..1eb72727df667 100644 --- a/compiler/rustc_ast_lowering/src/errors.rs +++ b/compiler/rustc_ast_lowering/src/errors.rs @@ -4,17 +4,17 @@ use rustc_macros::{Diagnostic, Subdiagnostic}; use rustc_span::{Ident, Span, Symbol}; #[derive(Diagnostic)] -#[diag(ast_lowering_generic_type_with_parentheses, code = E0214)] +#[diag("parenthesized type parameters may only be used with a `Fn` trait", code = E0214)] pub(crate) struct GenericTypeWithParentheses { #[primary_span] - #[label] + #[label("only `Fn` traits may use parentheses")] pub span: Span, #[subdiagnostic] pub sub: Option, } #[derive(Subdiagnostic)] -#[multipart_suggestion(ast_lowering_use_angle_brackets, applicability = "maybe-incorrect")] +#[multipart_suggestion("use angle brackets instead", applicability = "maybe-incorrect")] pub(crate) struct UseAngleBrackets { #[suggestion_part(code = "<")] pub open_param: Span, @@ -23,11 +23,11 @@ pub(crate) struct UseAngleBrackets { } #[derive(Diagnostic)] -#[diag(ast_lowering_invalid_abi, code = E0703)] -#[note] +#[diag("invalid ABI: found `{$abi}`", code = E0703)] +#[note("invoke `{$command}` for a full list of supported calling conventions")] pub(crate) struct InvalidAbi { #[primary_span] - #[label] + #[label("invalid ABI")] pub span: Span, pub abi: Symbol, pub command: String, @@ -36,16 +36,16 @@ pub(crate) struct InvalidAbi { } #[derive(Diagnostic)] -#[diag(ast_lowering_default_field_in_tuple)] +#[diag("default fields are not supported in tuple structs")] pub(crate) struct TupleStructWithDefault { #[primary_span] - #[label] + #[label("default fields are only supported on structs")] pub span: Span, } #[derive(Subdiagnostic)] #[suggestion( - ast_lowering_invalid_abi_suggestion, + "there's a similarly named valid ABI `{$suggestion}`", code = "\"{suggestion}\"", applicability = "maybe-incorrect", style = "verbose" @@ -57,7 +57,7 @@ pub(crate) struct InvalidAbiSuggestion { } #[derive(Diagnostic)] -#[diag(ast_lowering_assoc_ty_parentheses)] +#[diag("parenthesized generic arguments cannot be used in associated type constraints")] pub(crate) struct AssocTyParentheses { #[primary_span] pub span: Span, @@ -67,12 +67,12 @@ pub(crate) struct AssocTyParentheses { #[derive(Subdiagnostic)] pub(crate) enum AssocTyParenthesesSub { - #[multipart_suggestion(ast_lowering_remove_parentheses)] + #[multipart_suggestion("remove these parentheses")] Empty { #[suggestion_part(code = "")] parentheses_span: Span, }, - #[multipart_suggestion(ast_lowering_use_angle_brackets)] + #[multipart_suggestion("use angle brackets instead")] NotEmpty { #[suggestion_part(code = "<")] open_param: Span, @@ -82,8 +82,8 @@ pub(crate) enum AssocTyParenthesesSub { } #[derive(Diagnostic)] -#[diag(ast_lowering_misplaced_impl_trait, code = E0562)] -#[note] +#[diag("`impl Trait` is not allowed in {$position}", code = E0562)] +#[note("`impl Trait` is only allowed in arguments and return types of functions and methods")] pub(crate) struct MisplacedImplTrait<'a> { #[primary_span] pub span: Span, @@ -91,97 +91,106 @@ pub(crate) struct MisplacedImplTrait<'a> { } #[derive(Diagnostic)] -#[diag(ast_lowering_assoc_ty_binding_in_dyn)] +#[diag("associated type bounds are not allowed in `dyn` types")] pub(crate) struct MisplacedAssocTyBinding { #[primary_span] pub span: Span, - #[suggestion(code = " = impl", applicability = "maybe-incorrect", style = "verbose")] + #[suggestion( + "use `impl Trait` to introduce a type instead", + code = " = impl", + applicability = "maybe-incorrect", + style = "verbose" + )] pub suggestion: Option, } #[derive(Diagnostic)] -#[diag(ast_lowering_underscore_expr_lhs_assign)] +#[diag("in expressions, `_` can only be used on the left-hand side of an assignment")] pub(crate) struct UnderscoreExprLhsAssign { #[primary_span] - #[label] + #[label("`_` not allowed here")] pub span: Span, } #[derive(Diagnostic)] -#[diag(ast_lowering_await_only_in_async_fn_and_blocks, code = E0728)] +#[diag("`await` is only allowed inside `async` functions and blocks", code = E0728)] pub(crate) struct AwaitOnlyInAsyncFnAndBlocks { #[primary_span] - #[label] + #[label("only allowed inside `async` functions and blocks")] pub await_kw_span: Span, - #[label(ast_lowering_this_not_async)] + #[label("this is not `async`")] pub item_span: Option, } #[derive(Diagnostic)] -#[diag(ast_lowering_coroutine_too_many_parameters, code = E0628)] +#[diag("too many parameters for a coroutine (expected 0 or 1 parameters)", code = E0628)] pub(crate) struct CoroutineTooManyParameters { #[primary_span] pub fn_decl_span: Span, } #[derive(Diagnostic)] -#[diag(ast_lowering_closure_cannot_be_static, code = E0697)] +#[diag("closures cannot be static", code = E0697)] pub(crate) struct ClosureCannotBeStatic { #[primary_span] pub fn_decl_span: Span, } #[derive(Diagnostic)] -#[diag(ast_lowering_functional_record_update_destructuring_assignment)] +#[diag("functional record updates are not allowed in destructuring assignments")] pub(crate) struct FunctionalRecordUpdateDestructuringAssignment { #[primary_span] - #[suggestion(code = "", applicability = "machine-applicable")] + #[suggestion( + "consider removing the trailing pattern", + code = "", + applicability = "machine-applicable" + )] pub span: Span, } #[derive(Diagnostic)] -#[diag(ast_lowering_async_coroutines_not_supported, code = E0727)] +#[diag("`async` coroutines are not yet supported", code = E0727)] pub(crate) struct AsyncCoroutinesNotSupported { #[primary_span] pub span: Span, } #[derive(Diagnostic)] -#[diag(ast_lowering_inline_asm_unsupported_target, code = E0472)] +#[diag("inline assembly is unsupported on this target", code = E0472)] pub(crate) struct InlineAsmUnsupportedTarget { #[primary_span] pub span: Span, } #[derive(Diagnostic)] -#[diag(ast_lowering_att_syntax_only_x86)] +#[diag("the `att_syntax` option is only supported on x86")] pub(crate) struct AttSyntaxOnlyX86 { #[primary_span] pub span: Span, } #[derive(Diagnostic)] -#[diag(ast_lowering_abi_specified_multiple_times)] +#[diag("`{$prev_name}` ABI specified multiple times")] pub(crate) struct AbiSpecifiedMultipleTimes { #[primary_span] pub abi_span: Span, pub prev_name: Symbol, - #[label] + #[label("previously specified here")] pub prev_span: Span, - #[note] + #[note("these ABIs are equivalent on the current target")] pub equivalent: bool, } #[derive(Diagnostic)] -#[diag(ast_lowering_clobber_abi_not_supported)] +#[diag("`clobber_abi` is not supported on this target")] pub(crate) struct ClobberAbiNotSupported { #[primary_span] pub abi_span: Span, } #[derive(Diagnostic)] -#[note] -#[diag(ast_lowering_invalid_abi_clobber_abi)] +#[note("the following ABIs are supported on this target: {$supported_abis}")] +#[diag("invalid ABI for `clobber_abi`")] pub(crate) struct InvalidAbiClobberAbi { #[primary_span] pub abi_span: Span, @@ -189,7 +198,7 @@ pub(crate) struct InvalidAbiClobberAbi { } #[derive(Diagnostic)] -#[diag(ast_lowering_invalid_register)] +#[diag("invalid register `{$reg}`: {$error}")] pub(crate) struct InvalidRegister<'a> { #[primary_span] pub op_span: Span, @@ -198,8 +207,10 @@ pub(crate) struct InvalidRegister<'a> { } #[derive(Diagnostic)] -#[note] -#[diag(ast_lowering_invalid_register_class)] +#[note( + "the following register classes are supported on this target: {$supported_register_classes}" +)] +#[diag("invalid register class `{$reg_class}`: unknown register class")] pub(crate) struct InvalidRegisterClass { #[primary_span] pub op_span: Span, @@ -208,12 +219,12 @@ pub(crate) struct InvalidRegisterClass { } #[derive(Diagnostic)] -#[diag(ast_lowering_invalid_asm_template_modifier_reg_class)] +#[diag("invalid asm template modifier for this register class")] pub(crate) struct InvalidAsmTemplateModifierRegClass { #[primary_span] - #[label(ast_lowering_template_modifier)] + #[label("template modifier")] pub placeholder_span: Span, - #[label(ast_lowering_argument)] + #[label("argument")] pub op_span: Span, #[subdiagnostic] pub sub: InvalidAsmTemplateModifierRegClassSub, @@ -221,44 +232,48 @@ pub(crate) struct InvalidAsmTemplateModifierRegClass { #[derive(Subdiagnostic)] pub(crate) enum InvalidAsmTemplateModifierRegClassSub { - #[note(ast_lowering_support_modifiers)] + #[note( + "the `{$class_name}` register class supports the following template modifiers: {$modifiers}" + )] SupportModifier { class_name: Symbol, modifiers: String }, - #[note(ast_lowering_does_not_support_modifiers)] + #[note("the `{$class_name}` register class does not support template modifiers")] DoesNotSupportModifier { class_name: Symbol }, } #[derive(Diagnostic)] -#[diag(ast_lowering_invalid_asm_template_modifier_const)] +#[diag("asm template modifiers are not allowed for `const` arguments")] pub(crate) struct InvalidAsmTemplateModifierConst { #[primary_span] - #[label(ast_lowering_template_modifier)] + #[label("template modifier")] pub placeholder_span: Span, - #[label(ast_lowering_argument)] + #[label("argument")] pub op_span: Span, } #[derive(Diagnostic)] -#[diag(ast_lowering_invalid_asm_template_modifier_sym)] +#[diag("asm template modifiers are not allowed for `sym` arguments")] pub(crate) struct InvalidAsmTemplateModifierSym { #[primary_span] - #[label(ast_lowering_template_modifier)] + #[label("template modifier")] pub placeholder_span: Span, - #[label(ast_lowering_argument)] + #[label("argument")] pub op_span: Span, } #[derive(Diagnostic)] -#[diag(ast_lowering_invalid_asm_template_modifier_label)] +#[diag("asm template modifiers are not allowed for `label` arguments")] pub(crate) struct InvalidAsmTemplateModifierLabel { #[primary_span] - #[label(ast_lowering_template_modifier)] + #[label("template modifier")] pub placeholder_span: Span, - #[label(ast_lowering_argument)] + #[label("argument")] pub op_span: Span, } #[derive(Diagnostic)] -#[diag(ast_lowering_register_class_only_clobber)] +#[diag( + "register class `{$reg_class_name}` can only be used as a clobber, not as an input or output" +)] pub(crate) struct RegisterClassOnlyClobber { #[primary_span] pub op_span: Span, @@ -266,7 +281,7 @@ pub(crate) struct RegisterClassOnlyClobber { } #[derive(Diagnostic)] -#[diag(ast_lowering_register_class_only_clobber_stable)] +#[diag("register class `{$reg_class_name}` can only be used as a clobber in stable")] pub(crate) struct RegisterClassOnlyClobberStable { #[primary_span] pub op_span: Span, @@ -274,27 +289,27 @@ pub(crate) struct RegisterClassOnlyClobberStable { } #[derive(Diagnostic)] -#[diag(ast_lowering_register_conflict)] +#[diag("register `{$reg1_name}` conflicts with register `{$reg2_name}`")] pub(crate) struct RegisterConflict<'a> { #[primary_span] - #[label(ast_lowering_register1)] + #[label("register `{$reg1_name}`")] pub op_span1: Span, - #[label(ast_lowering_register2)] + #[label("register `{$reg2_name}`")] pub op_span2: Span, pub reg1_name: &'a str, pub reg2_name: &'a str, - #[help] + #[help("use `lateout` instead of `out` to avoid conflict")] pub in_out: Option, } #[derive(Diagnostic)] -#[help] -#[diag(ast_lowering_sub_tuple_binding)] +#[help("remove this and bind each tuple field independently")] +#[diag("`{$ident_name} @` is not allowed in a {$ctx}")] pub(crate) struct SubTupleBinding<'a> { #[primary_span] - #[label] + #[label("this is only allowed in slice patterns")] #[suggestion( - ast_lowering_sub_tuple_binding_suggestion, + "if you don't need to use the contents of {$ident}, discard the tuple's remaining fields", style = "verbose", code = "..", applicability = "maybe-incorrect" @@ -306,63 +321,67 @@ pub(crate) struct SubTupleBinding<'a> { } #[derive(Diagnostic)] -#[diag(ast_lowering_extra_double_dot)] +#[diag("`..` can only be used once per {$ctx} pattern")] pub(crate) struct ExtraDoubleDot<'a> { #[primary_span] - #[label] + #[label("can only be used once per {$ctx} pattern")] pub span: Span, - #[label(ast_lowering_previously_used_here)] + #[label("previously used here")] pub prev_span: Span, pub ctx: &'a str, } #[derive(Diagnostic)] -#[note] -#[diag(ast_lowering_misplaced_double_dot)] +#[note("only allowed in tuple, tuple struct, and slice patterns")] +#[diag("`..` patterns are not allowed here")] pub(crate) struct MisplacedDoubleDot { #[primary_span] pub span: Span, } #[derive(Diagnostic)] -#[diag(ast_lowering_match_arm_with_no_body)] +#[diag("`match` arm with no body")] pub(crate) struct MatchArmWithNoBody { #[primary_span] pub span: Span, - #[suggestion(code = " => todo!(),", applicability = "has-placeholders")] + #[suggestion( + "add a body after the pattern", + code = " => todo!(),", + applicability = "has-placeholders" + )] pub suggestion: Span, } #[derive(Diagnostic)] -#[diag(ast_lowering_never_pattern_with_body)] +#[diag("a never pattern is always unreachable")] pub(crate) struct NeverPatternWithBody { #[primary_span] - #[label] - #[suggestion(code = "", applicability = "maybe-incorrect")] + #[label("this will never be executed")] + #[suggestion("remove this expression", code = "", applicability = "maybe-incorrect")] pub span: Span, } #[derive(Diagnostic)] -#[diag(ast_lowering_never_pattern_with_guard)] +#[diag("a guard on a never pattern will never be run")] pub(crate) struct NeverPatternWithGuard { #[primary_span] - #[suggestion(code = "", applicability = "maybe-incorrect")] + #[suggestion("remove this guard", code = "", applicability = "maybe-incorrect")] pub span: Span, } #[derive(Diagnostic)] -#[diag(ast_lowering_arbitrary_expression_in_pattern)] +#[diag("arbitrary expressions aren't allowed in patterns")] pub(crate) struct ArbitraryExpressionInPattern { #[primary_span] pub span: Span, - #[note(ast_lowering_pattern_from_macro_note)] + #[note("the `expr` fragment specifier forces the metavariable's content to be an expression")] pub pattern_from_macro_note: bool, - #[help(ast_lowering_const_block_in_pattern_help)] + #[help("use a named `const`-item or an `if`-guard (`x if x == const {\"{ ... }\"}`) instead")] pub const_block_in_pattern_help: bool, } #[derive(Diagnostic)] -#[diag(ast_lowering_inclusive_range_with_no_end)] +#[diag("inclusive range with no end")] pub(crate) struct InclusiveRangeWithNoEnd { #[primary_span] pub span: Span, @@ -370,7 +389,7 @@ pub(crate) struct InclusiveRangeWithNoEnd { #[derive(Subdiagnostic)] #[multipart_suggestion( - ast_lowering_bad_return_type_notation_output_suggestion, + "use the right argument notation and remove the return type", applicability = "machine-applicable", style = "verbose" )] @@ -384,26 +403,36 @@ pub(crate) struct RTNSuggestion { #[derive(Diagnostic)] pub(crate) enum BadReturnTypeNotation { - #[diag(ast_lowering_bad_return_type_notation_inputs)] + #[diag("argument types not allowed with return type notation")] Inputs { #[primary_span] - #[suggestion(code = "(..)", applicability = "machine-applicable", style = "verbose")] + #[suggestion( + "remove the input types", + code = "(..)", + applicability = "machine-applicable", + style = "verbose" + )] span: Span, }, - #[diag(ast_lowering_bad_return_type_notation_output)] + #[diag("return type not allowed with return type notation")] Output { #[primary_span] span: Span, #[subdiagnostic] suggestion: RTNSuggestion, }, - #[diag(ast_lowering_bad_return_type_notation_needs_dots)] + #[diag("return type notation arguments must be elided with `..`")] NeedsDots { #[primary_span] - #[suggestion(code = "(..)", applicability = "machine-applicable", style = "verbose")] + #[suggestion( + "use the correct syntax by adding `..` to the arguments", + code = "(..)", + applicability = "machine-applicable", + style = "verbose" + )] span: Span, }, - #[diag(ast_lowering_bad_return_type_notation_position)] + #[diag("return type notation not allowed in this position yet")] Position { #[primary_span] span: Span, @@ -411,14 +440,14 @@ pub(crate) enum BadReturnTypeNotation { } #[derive(Diagnostic)] -#[diag(ast_lowering_generic_param_default_in_binder)] +#[diag("defaults for generic parameters are not allowed in `for<...>` binders")] pub(crate) struct GenericParamDefaultInBinder { #[primary_span] pub span: Span, } #[derive(Diagnostic)] -#[diag(ast_lowering_async_bound_not_on_trait)] +#[diag("`async` bound modifier only allowed on trait, not `{$descr}`")] pub(crate) struct AsyncBoundNotOnTrait { #[primary_span] pub span: Span, @@ -426,30 +455,37 @@ pub(crate) struct AsyncBoundNotOnTrait { } #[derive(Diagnostic)] -#[diag(ast_lowering_async_bound_only_for_fn_traits)] +#[diag("`async` bound modifier only allowed on `Fn`/`FnMut`/`FnOnce` traits")] pub(crate) struct AsyncBoundOnlyForFnTraits { #[primary_span] pub span: Span, } #[derive(Diagnostic)] -#[diag(ast_lowering_no_precise_captures_on_apit)] +#[diag("`use<...>` precise capturing syntax not allowed in argument-position `impl Trait`")] pub(crate) struct NoPreciseCapturesOnApit { #[primary_span] pub span: Span, } #[derive(Diagnostic)] -#[diag(ast_lowering_yield_in_closure)] +#[diag("`yield` can only be used in `#[coroutine]` closures, or `gen` blocks")] pub(crate) struct YieldInClosure { #[primary_span] pub span: Span, - #[suggestion(code = "#[coroutine] ", applicability = "maybe-incorrect", style = "verbose")] + #[suggestion( + "use `#[coroutine]` to make this closure a coroutine", + code = "#[coroutine] ", + applicability = "maybe-incorrect", + style = "verbose" + )] pub suggestion: Option, } #[derive(Diagnostic)] -#[diag(ast_lowering_invalid_legacy_const_generic_arg)] +#[diag( + "invalid argument to a legacy const generic: cannot have const blocks, closures, async blocks or items" +)] pub(crate) struct InvalidLegacyConstGenericArg { #[primary_span] pub span: Span, @@ -459,7 +495,7 @@ pub(crate) struct InvalidLegacyConstGenericArg { #[derive(Subdiagnostic)] #[multipart_suggestion( - ast_lowering_invalid_legacy_const_generic_arg_suggestion, + "try using a const generic argument instead", applicability = "maybe-incorrect" )] pub(crate) struct UseConstGenericArg { @@ -472,21 +508,21 @@ pub(crate) struct UseConstGenericArg { } #[derive(Diagnostic)] -#[diag(ast_lowering_union_default_field_values)] +#[diag("unions cannot have default field values")] pub(crate) struct UnionWithDefault { #[primary_span] pub span: Span, } #[derive(Diagnostic)] -#[diag(ast_lowering_delegation_unresolved_callee)] +#[diag("failed to resolve delegation callee")] pub(crate) struct UnresolvedDelegationCallee { #[primary_span] pub span: Span, } #[derive(Diagnostic)] -#[diag(ast_lowering_delegation_cycle_in_signature_resolution)] +#[diag("encountered a cycle during delegation signature resolution")] pub(crate) struct CycleInDelegationSignatureResolution { #[primary_span] pub span: Span, diff --git a/compiler/rustc_ast_lowering/src/expr.rs b/compiler/rustc_ast_lowering/src/expr.rs index 9fbfeb7a11e6e..051bebfbec00c 100644 --- a/compiler/rustc_ast_lowering/src/expr.rs +++ b/compiler/rustc_ast_lowering/src/expr.rs @@ -5,6 +5,7 @@ use std::sync::Arc; use rustc_ast::*; use rustc_ast_pretty::pprust::expr_to_string; use rustc_data_structures::stack::ensure_sufficient_stack; +use rustc_errors::inline_fluent; use rustc_hir as hir; use rustc_hir::attrs::AttributeKind; use rustc_hir::def::{DefKind, Res}; @@ -28,9 +29,7 @@ use super::{ GenericArgsMode, ImplTraitContext, LoweringContext, ParamMode, ResolverAstLoweringExt, }; use crate::errors::{InvalidLegacyConstGenericArg, UseConstGenericArg, YieldInClosure}; -use crate::{ - AllowReturnTypeNotation, FnDeclKind, ImplTraitPosition, TryBlockScope, fluent_generated, -}; +use crate::{AllowReturnTypeNotation, FnDeclKind, ImplTraitPosition, TryBlockScope}; struct WillCreateDefIdsVisitor {} @@ -1703,7 +1702,7 @@ impl<'hir> LoweringContext<'_, 'hir> { &self.tcx.sess, sym::yield_expr, span, - fluent_generated::ast_lowering_yield, + inline_fluent!("yield syntax is experimental"), ) .emit(); } diff --git a/compiler/rustc_ast_lowering/src/lib.rs b/compiler/rustc_ast_lowering/src/lib.rs index 8c6ee9d6bc630..e4f431fd2431c 100644 --- a/compiler/rustc_ast_lowering/src/lib.rs +++ b/compiler/rustc_ast_lowering/src/lib.rs @@ -88,8 +88,6 @@ mod pat; mod path; pub mod stability; -rustc_fluent_macro::fluent_messages! { "../messages.ftl" } - struct LoweringContext<'a, 'hir> { tcx: TyCtxt<'hir>, resolver: &'a mut ResolverAstLowering, diff --git a/compiler/rustc_attr_parsing/src/attributes/rustc_internal.rs b/compiler/rustc_attr_parsing/src/attributes/rustc_internal.rs index 8961dc47706f7..348882dc59fcd 100644 --- a/compiler/rustc_attr_parsing/src/attributes/rustc_internal.rs +++ b/compiler/rustc_attr_parsing/src/attributes/rustc_internal.rs @@ -1,12 +1,16 @@ use std::path::PathBuf; use rustc_ast::{LitIntType, LitKind, MetaItemLit}; -use rustc_hir::attrs::{BorrowckGraphvizFormatKind, RustcLayoutType, RustcMirKind}; +use rustc_hir::attrs::{ + BorrowckGraphvizFormatKind, RustcCleanAttribute, RustcCleanQueries, RustcLayoutType, + RustcMirKind, +}; use rustc_session::errors; +use rustc_span::Symbol; use super::prelude::*; use super::util::parse_single_integer; -use crate::session_diagnostics::RustcScalableVectorCountOutOfRange; +use crate::session_diagnostics::{AttributeRequiresOpt, RustcScalableVectorCountOutOfRange}; pub(crate) struct RustcMainParser; @@ -234,7 +238,7 @@ impl NoArgsAttributeParser for RustcLintUntrackedQueryInformationPa pub(crate) struct RustcObjectLifetimeDefaultParser; impl SingleAttributeParser for RustcObjectLifetimeDefaultParser { - const PATH: &[rustc_span::Symbol] = &[sym::rustc_object_lifetime_default]; + const PATH: &[Symbol] = &[sym::rustc_object_lifetime_default]; const ATTRIBUTE_ORDER: AttributeOrder = AttributeOrder::KeepInnermost; const ON_DUPLICATE: OnDuplicate = OnDuplicate::Error; const ALLOWED_TARGETS: AllowedTargets = AllowedTargets::AllowList(&[Allow(Target::Struct)]); @@ -271,7 +275,7 @@ impl SingleAttributeParser for RustcSimdMonomorphizeLaneLimitParser pub(crate) struct RustcScalableVectorParser; impl SingleAttributeParser for RustcScalableVectorParser { - const PATH: &[rustc_span::Symbol] = &[sym::rustc_scalable_vector]; + const PATH: &[Symbol] = &[sym::rustc_scalable_vector]; const ATTRIBUTE_ORDER: AttributeOrder = AttributeOrder::KeepInnermost; const ON_DUPLICATE: OnDuplicate = OnDuplicate::Error; const ALLOWED_TARGETS: AllowedTargets = AllowedTargets::AllowList(&[Allow(Target::Struct)]); @@ -344,7 +348,7 @@ impl NoArgsAttributeParser for RustcOffloadKernelParser { pub(crate) struct RustcLayoutParser; impl CombineAttributeParser for RustcLayoutParser { - const PATH: &[rustc_span::Symbol] = &[sym::rustc_layout]; + const PATH: &[Symbol] = &[sym::rustc_layout]; type Item = RustcLayoutType; @@ -401,7 +405,7 @@ impl CombineAttributeParser for RustcLayoutParser { pub(crate) struct RustcMirParser; impl CombineAttributeParser for RustcMirParser { - const PATH: &[rustc_span::Symbol] = &[sym::rustc_mir]; + const PATH: &[Symbol] = &[sym::rustc_mir]; type Item = RustcMirKind; @@ -497,3 +501,223 @@ impl NoArgsAttributeParser for RustcNonConstTraitMethodParser { ]); const CREATE: fn(Span) -> AttributeKind = |_| AttributeKind::RustcNonConstTraitMethod; } + +pub(crate) struct RustcCleanParser; + +impl CombineAttributeParser for RustcCleanParser { + const PATH: &[Symbol] = &[sym::rustc_clean]; + + type Item = RustcCleanAttribute; + + const CONVERT: ConvertFn = |items, _| AttributeKind::RustcClean(items); + + const ALLOWED_TARGETS: AllowedTargets = AllowedTargets::AllowList(&[ + // tidy-alphabetical-start + Allow(Target::AssocConst), + Allow(Target::AssocTy), + Allow(Target::Const), + Allow(Target::Enum), + Allow(Target::Expression), + Allow(Target::Field), + Allow(Target::Fn), + Allow(Target::ForeignMod), + Allow(Target::Impl { of_trait: false }), + Allow(Target::Impl { of_trait: true }), + Allow(Target::Method(MethodKind::Inherent)), + Allow(Target::Method(MethodKind::Trait { body: false })), + Allow(Target::Method(MethodKind::Trait { body: true })), + Allow(Target::Method(MethodKind::TraitImpl)), + Allow(Target::Mod), + Allow(Target::Static), + Allow(Target::Struct), + Allow(Target::Trait), + Allow(Target::TyAlias), + Allow(Target::Union), + // tidy-alphabetical-end + ]); + + const TEMPLATE: AttributeTemplate = + template!(List: &[r#"cfg = "...", /*opt*/ label = "...", /*opt*/ except = "...""#]); + + fn extend( + cx: &mut AcceptContext<'_, '_, S>, + args: &ArgParser, + ) -> impl IntoIterator { + if !cx.cx.sess.opts.unstable_opts.query_dep_graph { + cx.emit_err(AttributeRequiresOpt { span: cx.attr_span, opt: "-Z query-dep-graph" }); + } + let Some(list) = args.list() else { + cx.expected_list(cx.attr_span, args); + return None; + }; + let mut except = None; + let mut loaded_from_disk = None; + let mut cfg = None; + + for item in list.mixed() { + let Some((value, name)) = + item.meta_item().and_then(|m| Option::zip(m.args().name_value(), m.ident())) + else { + cx.expected_name_value(item.span(), None); + continue; + }; + let value_span = value.value_span; + let Some(value) = value.value_as_str() else { + cx.expected_string_literal(value_span, None); + continue; + }; + match name.name { + sym::cfg if cfg.is_some() => { + cx.duplicate_key(item.span(), sym::cfg); + } + + sym::cfg => { + cfg = Some(value); + } + sym::except if except.is_some() => { + cx.duplicate_key(item.span(), sym::except); + } + sym::except => { + let entries = + value.as_str().split(',').map(|s| Symbol::intern(s.trim())).collect(); + except = Some(RustcCleanQueries { entries, span: value_span }); + } + sym::loaded_from_disk if loaded_from_disk.is_some() => { + cx.duplicate_key(item.span(), sym::loaded_from_disk); + } + sym::loaded_from_disk => { + let entries = + value.as_str().split(',').map(|s| Symbol::intern(s.trim())).collect(); + loaded_from_disk = Some(RustcCleanQueries { entries, span: value_span }); + } + _ => { + cx.expected_specific_argument( + name.span, + &[sym::cfg, sym::except, sym::loaded_from_disk], + ); + } + } + } + let Some(cfg) = cfg else { + cx.expected_specific_argument(list.span, &[sym::cfg]); + return None; + }; + + Some(RustcCleanAttribute { span: cx.attr_span, cfg, except, loaded_from_disk }) + } +} + +pub(crate) struct RustcIfThisChangedParser; + +impl SingleAttributeParser for RustcIfThisChangedParser { + const PATH: &[Symbol] = &[sym::rustc_if_this_changed]; + + const ATTRIBUTE_ORDER: AttributeOrder = AttributeOrder::KeepOutermost; + + const ON_DUPLICATE: OnDuplicate = OnDuplicate::Error; + + const ALLOWED_TARGETS: AllowedTargets = AllowedTargets::AllowList(&[ + // tidy-alphabetical-start + Allow(Target::AssocConst), + Allow(Target::AssocTy), + Allow(Target::Const), + Allow(Target::Enum), + Allow(Target::Expression), + Allow(Target::Field), + Allow(Target::Fn), + Allow(Target::ForeignMod), + Allow(Target::Impl { of_trait: false }), + Allow(Target::Impl { of_trait: true }), + Allow(Target::Method(MethodKind::Inherent)), + Allow(Target::Method(MethodKind::Trait { body: false })), + Allow(Target::Method(MethodKind::Trait { body: true })), + Allow(Target::Method(MethodKind::TraitImpl)), + Allow(Target::Mod), + Allow(Target::Static), + Allow(Target::Struct), + Allow(Target::Trait), + Allow(Target::TyAlias), + Allow(Target::Union), + // tidy-alphabetical-end + ]); + + const TEMPLATE: AttributeTemplate = template!(Word, List: &["DepNode"]); + + fn convert(cx: &mut AcceptContext<'_, '_, S>, args: &ArgParser) -> Option { + if !cx.cx.sess.opts.unstable_opts.query_dep_graph { + cx.emit_err(AttributeRequiresOpt { span: cx.attr_span, opt: "-Z query-dep-graph" }); + } + match args { + ArgParser::NoArgs => Some(AttributeKind::RustcIfThisChanged(cx.attr_span, None)), + ArgParser::List(list) => { + let Some(item) = list.single() else { + cx.expected_single_argument(list.span); + return None; + }; + let Some(ident) = item.meta_item().and_then(|item| item.ident()) else { + cx.expected_identifier(item.span()); + return None; + }; + Some(AttributeKind::RustcIfThisChanged(cx.attr_span, Some(ident.name))) + } + ArgParser::NameValue(_) => { + cx.expected_list_or_no_args(cx.inner_span); + None + } + } + } +} + +pub(crate) struct RustcThenThisWouldNeedParser; + +impl CombineAttributeParser for RustcThenThisWouldNeedParser { + const PATH: &[Symbol] = &[sym::rustc_then_this_would_need]; + type Item = Ident; + + const CONVERT: ConvertFn = + |items, span| AttributeKind::RustcThenThisWouldNeed(span, items); + const ALLOWED_TARGETS: AllowedTargets = AllowedTargets::AllowList(&[ + // tidy-alphabetical-start + Allow(Target::AssocConst), + Allow(Target::AssocTy), + Allow(Target::Const), + Allow(Target::Enum), + Allow(Target::Expression), + Allow(Target::Field), + Allow(Target::Fn), + Allow(Target::ForeignMod), + Allow(Target::Impl { of_trait: false }), + Allow(Target::Impl { of_trait: true }), + Allow(Target::Method(MethodKind::Inherent)), + Allow(Target::Method(MethodKind::Trait { body: false })), + Allow(Target::Method(MethodKind::Trait { body: true })), + Allow(Target::Method(MethodKind::TraitImpl)), + Allow(Target::Mod), + Allow(Target::Static), + Allow(Target::Struct), + Allow(Target::Trait), + Allow(Target::TyAlias), + Allow(Target::Union), + // tidy-alphabetical-end + ]); + + const TEMPLATE: AttributeTemplate = template!(List: &["DepNode"]); + + fn extend( + cx: &mut AcceptContext<'_, '_, S>, + args: &ArgParser, + ) -> impl IntoIterator { + if !cx.cx.sess.opts.unstable_opts.query_dep_graph { + cx.emit_err(AttributeRequiresOpt { span: cx.attr_span, opt: "-Z query-dep-graph" }); + } + let Some(item) = args.list().and_then(|l| l.single()) else { + cx.expected_single_argument(cx.inner_span); + return None; + }; + let Some(ident) = item.meta_item().and_then(|item| item.ident()) else { + cx.expected_identifier(item.span()); + return None; + }; + Some(ident) + } +} diff --git a/compiler/rustc_attr_parsing/src/attributes/test_attrs.rs b/compiler/rustc_attr_parsing/src/attributes/test_attrs.rs index ec7cdd3624dc3..236d10d77b92a 100644 --- a/compiler/rustc_attr_parsing/src/attributes/test_attrs.rs +++ b/compiler/rustc_attr_parsing/src/attributes/test_attrs.rs @@ -113,3 +113,30 @@ impl NoArgsAttributeParser for RustcVarianceOfOpaquesParser { const ALLOWED_TARGETS: AllowedTargets = AllowedTargets::AllowList(&[Allow(Target::Crate)]); const CREATE: fn(Span) -> AttributeKind = |_| AttributeKind::RustcVarianceOfOpaques; } + +pub(crate) struct ReexportTestHarnessMainParser; + +impl SingleAttributeParser for ReexportTestHarnessMainParser { + const PATH: &[Symbol] = &[sym::reexport_test_harness_main]; + const ON_DUPLICATE: OnDuplicate = OnDuplicate::Error; + const ATTRIBUTE_ORDER: AttributeOrder = AttributeOrder::KeepOutermost; + const ALLOWED_TARGETS: AllowedTargets = AllowedTargets::AllowList(&[Allow(Target::Crate)]); + const TEMPLATE: AttributeTemplate = template!(NameValueStr: "name"); + + fn convert(cx: &mut AcceptContext<'_, '_, S>, args: &ArgParser) -> Option { + let Some(nv) = args.name_value() else { + cx.expected_name_value( + args.span().unwrap_or(cx.inner_span), + Some(sym::reexport_test_harness_main), + ); + return None; + }; + + let Some(name) = nv.value_as_str() else { + cx.expected_string_literal(nv.value_span, Some(nv.value_as_lit())); + return None; + }; + + Some(AttributeKind::ReexportTestHarnessMain(name)) + } +} diff --git a/compiler/rustc_attr_parsing/src/context.rs b/compiler/rustc_attr_parsing/src/context.rs index fa9f5b5859262..5abf299ec618c 100644 --- a/compiler/rustc_attr_parsing/src/context.rs +++ b/compiler/rustc_attr_parsing/src/context.rs @@ -153,8 +153,10 @@ attribute_parsers!( Combine, Combine, Combine, + Combine, Combine, Combine, + Combine, Combine, Combine, // tidy-alphabetical-end @@ -188,9 +190,11 @@ attribute_parsers!( Single, Single, Single, + Single, Single, Single, Single, + Single, Single, Single, Single, diff --git a/compiler/rustc_attr_parsing/src/session_diagnostics.rs b/compiler/rustc_attr_parsing/src/session_diagnostics.rs index b0a334210f746..6ca47e8d698b1 100644 --- a/compiler/rustc_attr_parsing/src/session_diagnostics.rs +++ b/compiler/rustc_attr_parsing/src/session_diagnostics.rs @@ -532,6 +532,14 @@ pub(crate) struct RustcScalableVectorCountOutOfRange { pub n: u128, } +#[derive(Diagnostic)] +#[diag("attribute requires {$opt} to be enabled")] +pub(crate) struct AttributeRequiresOpt { + #[primary_span] + pub span: Span, + pub opt: &'static str, +} + pub(crate) enum AttributeParseErrorReason<'a> { ExpectedNoArgs, ExpectedStringLiteral { diff --git a/compiler/rustc_codegen_llvm/src/builder/gpu_offload.rs b/compiler/rustc_codegen_llvm/src/builder/gpu_offload.rs index 402861eda8707..16ab18a568e84 100644 --- a/compiler/rustc_codegen_llvm/src/builder/gpu_offload.rs +++ b/compiler/rustc_codegen_llvm/src/builder/gpu_offload.rs @@ -347,7 +347,6 @@ pub(crate) struct OffloadKernelGlobals<'ll> { pub offload_sizes: &'ll llvm::Value, pub memtransfer_types: &'ll llvm::Value, pub region_id: &'ll llvm::Value, - pub offload_entry: &'ll llvm::Value, } fn gen_tgt_data_mappers<'ll>( @@ -468,8 +467,12 @@ pub(crate) fn gen_define_handling<'ll>( let c_section_name = CString::new("llvm_offload_entries").unwrap(); llvm::set_section(offload_entry, &c_section_name); - let result = - OffloadKernelGlobals { offload_sizes, memtransfer_types, region_id, offload_entry }; + cx.add_compiler_used_global(offload_entry); + + let result = OffloadKernelGlobals { offload_sizes, memtransfer_types, region_id }; + + // FIXME(Sa4dUs): use this global for constant offload sizes + cx.add_compiler_used_global(result.offload_sizes); cx.offload_kernel_cache.borrow_mut().insert(symbol, result); @@ -532,8 +535,7 @@ pub(crate) fn gen_call_handling<'ll, 'tcx>( offload_dims: &OffloadKernelDims<'ll>, ) { let cx = builder.cx; - let OffloadKernelGlobals { offload_sizes, offload_entry, memtransfer_types, region_id } = - offload_data; + let OffloadKernelGlobals { memtransfer_types, region_id, .. } = offload_data; let OffloadKernelDims { num_workgroups, threads_per_block, workgroup_dims, thread_dims } = offload_dims; @@ -548,20 +550,6 @@ pub(crate) fn gen_call_handling<'ll, 'tcx>( let num_args = types.len() as u64; let bb = builder.llbb(); - // FIXME(Sa4dUs): dummy loads are a temp workaround, we should find a proper way to prevent these - // variables from being optimized away - for val in [offload_sizes, offload_entry] { - unsafe { - let dummy = llvm::LLVMBuildLoad2( - &builder.llbuilder, - llvm::LLVMTypeOf(val), - val, - b"dummy\0".as_ptr() as *const _, - ); - llvm::LLVMSetVolatile(dummy, llvm::TRUE); - } - } - // Step 0) unsafe { llvm::LLVMRustPositionBuilderPastAllocas(&builder.llbuilder, builder.llfn()); diff --git a/compiler/rustc_codegen_ssa/Cargo.toml b/compiler/rustc_codegen_ssa/Cargo.toml index 3d045a02fef12..8642206351201 100644 --- a/compiler/rustc_codegen_ssa/Cargo.toml +++ b/compiler/rustc_codegen_ssa/Cargo.toml @@ -18,7 +18,6 @@ rustc_ast = { path = "../rustc_ast" } rustc_attr_parsing = { path = "../rustc_attr_parsing" } rustc_data_structures = { path = "../rustc_data_structures" } rustc_errors = { path = "../rustc_errors" } -rustc_fluent_macro = { path = "../rustc_fluent_macro" } rustc_fs_util = { path = "../rustc_fs_util" } rustc_hashes = { path = "../rustc_hashes" } rustc_hir = { path = "../rustc_hir" } diff --git a/compiler/rustc_codegen_ssa/messages.ftl b/compiler/rustc_codegen_ssa/messages.ftl deleted file mode 100644 index a49f411a7df62..0000000000000 --- a/compiler/rustc_codegen_ssa/messages.ftl +++ /dev/null @@ -1,397 +0,0 @@ -codegen_ssa_L4Bender_exporting_symbols_unimplemented = exporting symbols not implemented yet for L4Bender - -codegen_ssa_aarch64_softfloat_neon = enabling the `neon` target feature on the current target is unsound due to ABI issues - -codegen_ssa_add_native_library = failed to add native library {$library_path}: {$error} - -codegen_ssa_aix_strip_not_used = using host's `strip` binary to cross-compile to AIX which is not guaranteed to work - -codegen_ssa_archive_build_failure = failed to build archive at `{$path}`: {$error} - -codegen_ssa_binary_output_to_tty = option `-o` or `--emit` is used to write binary output type `{$shorthand}` to stdout, but stdout is a tty - -codegen_ssa_bpf_staticlib_not_supported = linking static libraries is not supported for BPF - -codegen_ssa_cgu_not_recorded = - CGU-reuse for `{$cgu_user_name}` is (mangled: `{$cgu_name}`) was not recorded - -codegen_ssa_check_installed_visual_studio = please ensure that Visual Studio 2017 or later, or Build Tools for Visual Studio were installed with the Visual C++ option. - -codegen_ssa_compiler_builtins_cannot_call = - `compiler_builtins` cannot call functions through upstream monomorphizations; encountered invalid call from `{$caller}` to `{$callee}` - -codegen_ssa_copy_path = could not copy {$from} to {$to}: {$error} - -codegen_ssa_copy_path_buf = unable to copy {$source_file} to {$output_path}: {$error} - -codegen_ssa_cpu_required = target requires explicitly specifying a cpu with `-C target-cpu` - -codegen_ssa_create_temp_dir = couldn't create a temp dir: {$error} - -codegen_ssa_dlltool_fail_import_library = - dlltool could not create import library with {$dlltool_path} {$dlltool_args}: - {$stdout} - {$stderr} - -codegen_ssa_dynamic_linking_with_lto = - cannot prefer dynamic linking when performing LTO - .note = only 'staticlib', 'bin', and 'cdylib' outputs are supported with LTO - -codegen_ssa_error_calling_dlltool = - error calling dlltool '{$dlltool_path}': {$error} - -codegen_ssa_error_creating_import_library = - error creating import library for {$lib_name}: {$error} - -codegen_ssa_error_creating_remark_dir = failed to create remark directory: {$error} - -codegen_ssa_error_writing_def_file = - error writing .DEF file: {$error} - -codegen_ssa_extern_funcs_not_found = some `extern` functions couldn't be found; some native libraries may need to be installed or have their path specified - -codegen_ssa_extract_bundled_libs_archive_member = failed to get data from archive member '{$rlib}': {$error} -codegen_ssa_extract_bundled_libs_convert_name = failed to convert name '{$rlib}': {$error} -codegen_ssa_extract_bundled_libs_mmap_file = failed to mmap file '{$rlib}': {$error} -codegen_ssa_extract_bundled_libs_open_file = failed to open file '{$rlib}': {$error} -codegen_ssa_extract_bundled_libs_parse_archive = failed to parse archive '{$rlib}': {$error} -codegen_ssa_extract_bundled_libs_read_entry = failed to read entry '{$rlib}': {$error} -codegen_ssa_extract_bundled_libs_write_file = failed to write file '{$rlib}': {$error} - -codegen_ssa_failed_to_get_layout = failed to get layout for {$ty}: {$err} - -codegen_ssa_failed_to_write = failed to write {$path}: {$error} - -codegen_ssa_feature_not_valid = the feature named `{$feature}` is not valid for this target - .label = `{$feature}` is not valid for this target - .help = consider removing the leading `+` in the feature name - -codegen_ssa_field_associated_value_expected = associated value expected for `{$name}` - -codegen_ssa_forbidden_ctarget_feature = - target feature `{$feature}` cannot be {$enabled} with `-Ctarget-feature`: {$reason} - .note = this was previously accepted by the compiler but is being phased out; it will become a hard error in a future release! -codegen_ssa_forbidden_ctarget_feature_issue = for more information, see issue #116344 - -codegen_ssa_forbidden_target_feature_attr = - target feature `{$feature}` cannot be enabled with `#[target_feature]`: {$reason} - -codegen_ssa_ignoring_emit_path = ignoring emit path because multiple .{$extension} files were produced - -codegen_ssa_ignoring_output = ignoring -o because multiple .{$extension} files were produced - -codegen_ssa_incorrect_cgu_reuse_type = - CGU-reuse for `{$cgu_user_name}` is `{$actual_reuse}` but should be {$at_least -> - [one] {"at least "} - *[other] {""} - }`{$expected_reuse}` - -codegen_ssa_insufficient_vs_code_product = VS Code is a different product, and is not sufficient. - -codegen_ssa_invalid_monomorphization_basic_float_type = invalid monomorphization of `{$name}` intrinsic: expected basic float type, found `{$ty}` - -codegen_ssa_invalid_monomorphization_basic_integer_or_ptr_type = invalid monomorphization of `{$name}` intrinsic: expected basic integer or pointer type, found `{$ty}` - -codegen_ssa_invalid_monomorphization_basic_integer_type = invalid monomorphization of `{$name}` intrinsic: expected basic integer type, found `{$ty}` - -codegen_ssa_invalid_monomorphization_cannot_return = invalid monomorphization of `{$name}` intrinsic: cannot return `{$ret_ty}`, expected `u{$expected_int_bits}` or `[u8; {$expected_bytes}]` - -codegen_ssa_invalid_monomorphization_cast_wide_pointer = invalid monomorphization of `{$name}` intrinsic: cannot cast wide pointer `{$ty}` - -codegen_ssa_invalid_monomorphization_expected_element_type = invalid monomorphization of `{$name}` intrinsic: expected element type `{$expected_element}` of second argument `{$second_arg}` to be a pointer to the element type `{$in_elem}` of the first argument `{$in_ty}`, found `{$expected_element}` != `{$mutability} {$in_elem}` - -codegen_ssa_invalid_monomorphization_expected_pointer = invalid monomorphization of `{$name}` intrinsic: expected pointer, got `{$ty}` - -codegen_ssa_invalid_monomorphization_expected_return_type = invalid monomorphization of `{$name}` intrinsic: expected return type `{$in_ty}`, found `{$ret_ty}` - -codegen_ssa_invalid_monomorphization_expected_usize = invalid monomorphization of `{$name}` intrinsic: expected `usize`, got `{$ty}` - -codegen_ssa_invalid_monomorphization_expected_vector_element_type = invalid monomorphization of `{$name}` intrinsic: expected element type `{$expected_element}` of vector type `{$vector_type}` to be a signed or unsigned integer type - -codegen_ssa_invalid_monomorphization_float_to_int_unchecked = invalid monomorphization of `float_to_int_unchecked` intrinsic: expected basic float type, found `{$ty}` - -codegen_ssa_invalid_monomorphization_floating_point_type = invalid monomorphization of `{$name}` intrinsic: `{$in_ty}` is not a floating-point type - -codegen_ssa_invalid_monomorphization_floating_point_vector = invalid monomorphization of `{$name}` intrinsic: unsupported element type `{$f_ty}` of floating-point vector `{$in_ty}` - -codegen_ssa_invalid_monomorphization_inserted_type = invalid monomorphization of `{$name}` intrinsic: expected inserted type `{$in_elem}` (element of input `{$in_ty}`), found `{$out_ty}` - -codegen_ssa_invalid_monomorphization_invalid_bitmask = invalid monomorphization of `{$name}` intrinsic: invalid bitmask `{$mask_ty}`, expected `u{$expected_int_bits}` or `[u8; {$expected_bytes}]` - -codegen_ssa_invalid_monomorphization_mask_wrong_element_type = invalid monomorphization of `{$name}` intrinsic: expected mask element type to be an integer, found `{$ty}` - -codegen_ssa_invalid_monomorphization_mismatched_lengths = invalid monomorphization of `{$name}` intrinsic: mismatched lengths: mask length `{$m_len}` != other vector length `{$v_len}` - -codegen_ssa_invalid_monomorphization_non_scalable_type = invalid monomorphization of `{$name}` intrinsic: expected non-scalable type, found scalable type `{$ty}` -codegen_ssa_invalid_monomorphization_return_element = invalid monomorphization of `{$name}` intrinsic: expected return element type `{$in_elem}` (element of input `{$in_ty}`), found `{$ret_ty}` with element type `{$out_ty}` - -codegen_ssa_invalid_monomorphization_return_integer_type = invalid monomorphization of `{$name}` intrinsic: expected return type with integer elements, found `{$ret_ty}` with non-integer `{$out_ty}` - -codegen_ssa_invalid_monomorphization_return_length = invalid monomorphization of `{$name}` intrinsic: expected return type of length {$in_len}, found `{$ret_ty}` with length {$out_len} - -codegen_ssa_invalid_monomorphization_return_length_input_type = invalid monomorphization of `{$name}` intrinsic: expected return type with length {$in_len} (same as input type `{$in_ty}`), found `{$ret_ty}` with length {$out_len} - -codegen_ssa_invalid_monomorphization_return_type = invalid monomorphization of `{$name}` intrinsic: expected return type `{$in_elem}` (element of input `{$in_ty}`), found `{$ret_ty}` - -codegen_ssa_invalid_monomorphization_second_argument_length = invalid monomorphization of `{$name}` intrinsic: expected second argument with length {$in_len} (same as input type `{$in_ty}`), found `{$arg_ty}` with length {$out_len} - -codegen_ssa_invalid_monomorphization_simd_argument = invalid monomorphization of `{$name}` intrinsic: expected SIMD argument type, found non-SIMD `{$ty}` - -codegen_ssa_invalid_monomorphization_simd_first = invalid monomorphization of `{$name}` intrinsic: expected SIMD first type, found non-SIMD `{$ty}` - -codegen_ssa_invalid_monomorphization_simd_index_out_of_bounds = invalid monomorphization of `{$name}` intrinsic: SIMD index #{$arg_idx} is out of bounds (limit {$total_len}) - -codegen_ssa_invalid_monomorphization_simd_input = invalid monomorphization of `{$name}` intrinsic: expected SIMD input type, found non-SIMD `{$ty}` - -codegen_ssa_invalid_monomorphization_simd_return = invalid monomorphization of `{$name}` intrinsic: expected SIMD return type, found non-SIMD `{$ty}` - -codegen_ssa_invalid_monomorphization_simd_second = invalid monomorphization of `{$name}` intrinsic: expected SIMD second type, found non-SIMD `{$ty}` - -codegen_ssa_invalid_monomorphization_simd_shuffle = invalid monomorphization of `{$name}` intrinsic: simd_shuffle index must be a SIMD vector of `u32`, got `{$ty}` - -codegen_ssa_invalid_monomorphization_simd_third = invalid monomorphization of `{$name}` intrinsic: expected SIMD third type, found non-SIMD `{$ty}` - -codegen_ssa_invalid_monomorphization_third_argument_length = invalid monomorphization of `{$name}` intrinsic: expected third argument with length {$in_len} (same as input type `{$in_ty}`), found `{$arg_ty}` with length {$out_len} - -codegen_ssa_invalid_monomorphization_unrecognized_intrinsic = invalid monomorphization of `{$name}` intrinsic: unrecognized intrinsic `{$name}` - -codegen_ssa_invalid_monomorphization_unsupported_cast = invalid monomorphization of `{$name}` intrinsic: unsupported cast from `{$in_ty}` with element `{$in_elem}` to `{$ret_ty}` with element `{$out_elem}` - -codegen_ssa_invalid_monomorphization_unsupported_operation = invalid monomorphization of `{$name}` intrinsic: unsupported operation on `{$in_ty}` with element `{$in_elem}` - -codegen_ssa_invalid_monomorphization_unsupported_symbol = invalid monomorphization of `{$name}` intrinsic: unsupported {$symbol} from `{$in_ty}` with element `{$in_elem}` to `{$ret_ty}` - -codegen_ssa_invalid_monomorphization_unsupported_symbol_of_size = invalid monomorphization of `{$name}` intrinsic: unsupported {$symbol} from `{$in_ty}` with element `{$in_elem}` of size `{$size}` to `{$ret_ty}` - -codegen_ssa_ld64_unimplemented_modifier = `as-needed` modifier not implemented yet for ld64 - -codegen_ssa_lib_def_write_failure = failed to write lib.def file: {$error} - -codegen_ssa_link_exe_status_stack_buffer_overrun = 0xc0000409 is `STATUS_STACK_BUFFER_OVERRUN` - .abort_note = this may have been caused by a program abort and not a stack buffer overrun - .event_log_note = consider checking the Application Event Log for Windows Error Reporting events to see the fail fast error code - -codegen_ssa_link_exe_unexpected_error = `link.exe` returned an unexpected error - -codegen_ssa_link_script_unavailable = can only use link script when linking with GNU-like linker - -codegen_ssa_link_script_write_failure = failed to write link script to {$path}: {$error} - -codegen_ssa_linker_file_stem = couldn't extract file stem from specified linker - -codegen_ssa_linker_not_found = linker `{$linker_path}` not found - .note = {$error} - -codegen_ssa_linker_output = {$inner} - -codegen_ssa_linker_unsupported_modifier = `as-needed` modifier not supported for current linker - -codegen_ssa_linking_failed = linking with `{$linker_path}` failed: {$exit_status} - -codegen_ssa_lto_disallowed = lto can only be run for executables, cdylibs and static library outputs - -codegen_ssa_lto_dylib = lto cannot be used for `dylib` crate type without `-Zdylib-lto` - -codegen_ssa_lto_proc_macro = lto cannot be used for `proc-macro` crate type without `-Zdylib-lto` - -codegen_ssa_malformed_cgu_name = - found malformed codegen unit name `{$user_path}`. codegen units names must always start with the name of the crate (`{$crate_name}` in this case). - -codegen_ssa_missing_cpp_build_tool_component = or a necessary component may be missing from the "C++ build tools" workload - -codegen_ssa_missing_features = add the missing features in a `target_feature` attribute - -codegen_ssa_missing_query_depgraph = - found CGU-reuse attribute but `-Zquery-dep-graph` was not specified - -codegen_ssa_msvc_missing_linker = the msvc targets depend on the msvc linker but `link.exe` was not found - -codegen_ssa_multiple_external_func_decl = multiple declarations of external function `{$function}` from library `{$library_name}` have different calling conventions - -codegen_ssa_multiple_main_functions = entry symbol `main` declared multiple times - .help = did you use `#[no_mangle]` on `fn main`? Use `#![no_main]` to suppress the usual Rust-generated entry point - -codegen_ssa_no_field = no field `{$name}` - -codegen_ssa_no_module_named = - no module named `{$user_path}` (mangled: {$cgu_name}). available modules: {$cgu_names} - -codegen_ssa_no_natvis_directory = error enumerating natvis directory: {$error} - -codegen_ssa_no_saved_object_file = cached cgu {$cgu_name} should have an object file, but doesn't - -codegen_ssa_processing_dymutil_failed = processing debug info with `dsymutil` failed: {$status} - .note = {$output} - -codegen_ssa_read_file = failed to read file: {$message} - -codegen_ssa_repair_vs_build_tools = the Visual Studio build tools may need to be repaired using the Visual Studio installer - -codegen_ssa_requires_rust_abi = `#[track_caller]` requires Rust ABI - -codegen_ssa_rlib_archive_build_failure = failed to build archive from rlib at `{$path}`: {$error} - -codegen_ssa_rlib_incompatible_dependency_formats = `{$ty1}` and `{$ty2}` do not have equivalent dependency formats (`{$list1}` vs `{$list2}`) - -codegen_ssa_rlib_missing_format = could not find formats for rlibs - -codegen_ssa_rlib_not_found = could not find rlib for: `{$crate_name}` - -codegen_ssa_rlib_only_rmeta_found = could not find rlib for: `{$crate_name}`, found rmeta (metadata) file - -codegen_ssa_select_cpp_build_tool_workload = in the Visual Studio installer, ensure the "C++ build tools" workload is selected - -codegen_ssa_self_contained_linker_missing = the self-contained linker was requested, but it wasn't found in the target's sysroot, or in rustc's sysroot - -codegen_ssa_shuffle_indices_evaluation = could not evaluate shuffle_indices at compile time - -codegen_ssa_specify_libraries_to_link = use the `-l` flag to specify native libraries to link - -codegen_ssa_static_library_native_artifacts = link against the following native artifacts when linking against this static library. The order and any duplication can be significant on some platforms. - -codegen_ssa_static_library_native_artifacts_to_file = native artifacts to link against have been written to {$path}. The order and any duplication can be significant on some platforms. - -codegen_ssa_stripping_debug_info_failed = stripping debug info with `{$util}` failed: {$status} - .note = {$output} - -codegen_ssa_symbol_file_write_failure = failed to write symbols file: {$error} - -codegen_ssa_target_feature_disable_or_enable = - the target features {$features} must all be either enabled or disabled together - -codegen_ssa_target_feature_safe_trait = `#[target_feature(..)]` cannot be applied to safe trait method - .label = cannot be applied to safe trait method - .label_def = not an `unsafe` function - -codegen_ssa_thorin_decompress_data = failed to decompress compressed section - -codegen_ssa_thorin_duplicate_unit = duplicate split compilation unit ({$unit}) - -codegen_ssa_thorin_empty_unit = unit {$unit} in input DWARF object with no data - -codegen_ssa_thorin_gimli_read = {$error} -codegen_ssa_thorin_gimli_write = {$error} - -codegen_ssa_thorin_incompatible_index_version = incompatible `{$section}` index version: found version {$actual}, expected version {$format} - -codegen_ssa_thorin_invalid_input_kind = input is not an archive or elf object - -codegen_ssa_thorin_io = {$error} -codegen_ssa_thorin_missing_dwo_name = missing path attribute to DWARF object ({$id}) - -codegen_ssa_thorin_missing_referenced_unit = unit {$unit} referenced by executable was not found - -codegen_ssa_thorin_missing_required_section = input object missing required section `{$section}` - -codegen_ssa_thorin_mixed_input_encodings = input objects have mixed encodings - -codegen_ssa_thorin_multiple_debug_info_section = multiple `.debug_info.dwo` sections - -codegen_ssa_thorin_multiple_debug_types_section = multiple `.debug_types.dwo` sections in a package - -codegen_ssa_thorin_multiple_relocations = multiple relocations for section `{$section}` at offset {$offset} - -codegen_ssa_thorin_no_compilation_units = input object has no compilation units - -codegen_ssa_thorin_no_die = no top-level debugging information entry in compilation/type unit - -codegen_ssa_thorin_not_output_object_created = no output object was created from inputs - -codegen_ssa_thorin_not_split_unit = regular compilation unit in object (missing dwo identifier) - -codegen_ssa_thorin_object_read = {$error} -codegen_ssa_thorin_object_write = {$error} -codegen_ssa_thorin_offset_at_index = read offset at index {$index} of `.debug_str_offsets.dwo` section - -codegen_ssa_thorin_parse_archive_member = failed to parse archive member - -codegen_ssa_thorin_parse_index = failed to parse `{$section}` index section - -codegen_ssa_thorin_parse_input_archive_file = failed to parse input archive file - -codegen_ssa_thorin_parse_input_file_kind = failed to parse input file kind - -codegen_ssa_thorin_parse_input_object_file = failed to parse input object file - -codegen_ssa_thorin_parse_unit = failed to parse unit - -codegen_ssa_thorin_parse_unit_abbreviations = failed to parse unit abbreviations - -codegen_ssa_thorin_parse_unit_attribute = failed to parse unit attribute - -codegen_ssa_thorin_parse_unit_header = failed to parse unit header - -codegen_ssa_thorin_read_input_failure = failed to read input file - -codegen_ssa_thorin_relocation_with_invalid_symbol = relocation with invalid symbol for section `{$section}` at offset {$offset} - -codegen_ssa_thorin_row_not_in_index = row {$row} found in index's hash table not present in index - -codegen_ssa_thorin_section_not_in_row = section not found in unit's row in index - -codegen_ssa_thorin_section_without_name = section without name at offset {$offset} - -codegen_ssa_thorin_str_at_offset = read string at offset {$offset} of `.debug_str.dwo` section - -codegen_ssa_thorin_top_level_die_not_unit = top-level debugging information entry is not a compilation/type unit - -codegen_ssa_thorin_unit_not_in_index = unit {$unit} from input package is not in its index - -codegen_ssa_thorin_unsupported_relocation = unsupported relocation for section {$section} at offset {$offset} - -codegen_ssa_unable_to_exe_linker = could not exec the linker `{$linker_path}` - .note = {$error} - .command_note = {$command_formatted} - -codegen_ssa_unable_to_run = unable to run `{$util}`: {$error} - -codegen_ssa_unable_to_run_dsymutil = unable to run `dsymutil`: {$error} - -codegen_ssa_unable_to_write_debugger_visualizer = unable to write debugger visualizer file `{$path}`: {$error} - -codegen_ssa_unknown_archive_kind = - don't know how to build archive of type: {$kind} - -codegen_ssa_unknown_ctarget_feature = - unknown and unstable feature specified for `-Ctarget-feature`: `{$feature}` - .note = it is still passed through to the codegen backend, but use of this feature might be unsound and the behavior of this feature can change in the future - .possible_feature = you might have meant: `{$rust_feature}` - .consider_filing_feature_request = consider filing a feature request - -codegen_ssa_unknown_ctarget_feature_prefix = - unknown feature specified for `-Ctarget-feature`: `{$feature}` - .note = features must begin with a `+` to enable or `-` to disable it - -codegen_ssa_unknown_reuse_kind = unknown cgu-reuse-kind `{$kind}` specified - -codegen_ssa_unstable_ctarget_feature = - unstable feature specified for `-Ctarget-feature`: `{$feature}` - .note = this feature is not stably supported; its behavior can change in the future - -codegen_ssa_unsupported_link_self_contained = option `-C link-self-contained` is not supported on this target - -codegen_ssa_use_cargo_directive = use the `cargo:rustc-link-lib` directive to specify the native libraries to link with Cargo (see https://doc.rust-lang.org/cargo/reference/build-scripts.html#rustc-link-lib) - -codegen_ssa_version_script_write_failure = failed to write version script: {$error} - -codegen_ssa_visual_studio_not_installed = you may need to install Visual Studio build tools with the "C++ build tools" workload - -codegen_ssa_xcrun_about = - the SDK is needed by the linker to know where to find symbols in system libraries and for embedding the SDK version in the final object file - -codegen_ssa_xcrun_command_line_tools_insufficient = - when compiling for iOS, tvOS, visionOS or watchOS, you need a full installation of Xcode - -codegen_ssa_xcrun_failed_invoking = invoking `{$command_formatted}` to find {$sdk_name}.sdk failed: {$error} - -codegen_ssa_xcrun_found_developer_dir = found active developer directory at "{$developer_dir}" - -# `xcrun` already outputs a message about missing Xcode installation, so we only augment it with details about env vars. -codegen_ssa_xcrun_no_developer_dir = - pass the path of an Xcode installation via the DEVELOPER_DIR environment variable, or an SDK with the SDKROOT environment variable - -codegen_ssa_xcrun_sdk_path_warning = output of `xcrun` while finding {$sdk_name}.sdk - .note = {$stderr} - -codegen_ssa_xcrun_unsuccessful = failed running `{$command_formatted}` to find {$sdk_name}.sdk - .note = {$stdout}{$stderr} diff --git a/compiler/rustc_codegen_ssa/src/back/apple.rs b/compiler/rustc_codegen_ssa/src/back/apple.rs index 23808ade6c850..3ed5793d10c52 100644 --- a/compiler/rustc_codegen_ssa/src/back/apple.rs +++ b/compiler/rustc_codegen_ssa/src/back/apple.rs @@ -3,6 +3,7 @@ use std::path::PathBuf; use std::process::Command; use itertools::Itertools; +use rustc_errors::inline_fluent; use rustc_middle::middle::exported_symbols::SymbolExportKind; use rustc_session::Session; pub(super) use rustc_target::spec::apple::OSVersion; @@ -10,7 +11,6 @@ use rustc_target::spec::{Arch, Env, Os, Target}; use tracing::debug; use crate::errors::{XcrunError, XcrunSdkPathWarning}; -use crate::fluent_generated as fluent; #[cfg(test)] mod tests; @@ -185,19 +185,21 @@ pub(super) fn get_sdk_root(sess: &Session) -> Option { // FIXME(madsmtm): Make this a lint, to allow deny warnings to work. // (Or fix ). let mut diag = sess.dcx().create_warn(err); - diag.note(fluent::codegen_ssa_xcrun_about); + diag.note(inline_fluent!("the SDK is needed by the linker to know where to find symbols in system libraries and for embedding the SDK version in the final object file")); // Recognize common error cases, and give more Rust-specific error messages for those. if let Some(developer_dir) = xcode_select_developer_dir() { diag.arg("developer_dir", &developer_dir); - diag.note(fluent::codegen_ssa_xcrun_found_developer_dir); + diag.note(inline_fluent!( + "found active developer directory at \"{$developer_dir}\"" + )); if developer_dir.as_os_str().to_string_lossy().contains("CommandLineTools") { if sdk_name != "MacOSX" { - diag.help(fluent::codegen_ssa_xcrun_command_line_tools_insufficient); + diag.help(inline_fluent!("when compiling for iOS, tvOS, visionOS or watchOS, you need a full installation of Xcode")); } } } else { - diag.help(fluent::codegen_ssa_xcrun_no_developer_dir); + diag.help(inline_fluent!("pass the path of an Xcode installation via the DEVELOPER_DIR environment variable, or an SDK with the SDKROOT environment variable")); } diag.emit(); diff --git a/compiler/rustc_codegen_ssa/src/back/link.rs b/compiler/rustc_codegen_ssa/src/back/link.rs index 5a732382c9818..acc1c0b9f0de8 100644 --- a/compiler/rustc_codegen_ssa/src/back/link.rs +++ b/compiler/rustc_codegen_ssa/src/back/link.rs @@ -663,7 +663,7 @@ fn link_dwarf_object(sess: &Session, cg_results: &CodegenResults, executable_out } #[derive(LintDiagnostic)] -#[diag(codegen_ssa_linker_output)] +#[diag("{$inner}")] /// Translating this is kind of useless. We don't pass translation flags to the linker, so we'd just /// end up with inconsistent languages within the same diagnostic. struct LinkerOutput { diff --git a/compiler/rustc_codegen_ssa/src/errors.rs b/compiler/rustc_codegen_ssa/src/errors.rs index 6a97de4c2b132..742e05973ee58 100644 --- a/compiler/rustc_codegen_ssa/src/errors.rs +++ b/compiler/rustc_codegen_ssa/src/errors.rs @@ -9,6 +9,7 @@ use std::process::ExitStatus; use rustc_errors::codes::*; use rustc_errors::{ Diag, DiagArgValue, DiagCtxtHandle, Diagnostic, EmissionGuarantee, IntoDiagArg, Level, + inline_fluent, }; use rustc_macros::{Diagnostic, LintDiagnostic, Subdiagnostic}; use rustc_middle::ty::layout::LayoutError; @@ -17,10 +18,14 @@ use rustc_span::{Span, Symbol}; use crate::assert_module_sources::CguReuse; use crate::back::command::Command; -use crate::fluent_generated as fluent; #[derive(Diagnostic)] -#[diag(codegen_ssa_incorrect_cgu_reuse_type)] +#[diag( + "CGU-reuse for `{$cgu_user_name}` is `{$actual_reuse}` but should be {$at_least -> + [one] {\"at least \"} + *[other] {\"\"} + }`{$expected_reuse}`" +)] pub(crate) struct IncorrectCguReuseType<'a> { #[primary_span] pub span: Span, @@ -31,14 +36,14 @@ pub(crate) struct IncorrectCguReuseType<'a> { } #[derive(Diagnostic)] -#[diag(codegen_ssa_cgu_not_recorded)] +#[diag("CGU-reuse for `{$cgu_user_name}` is (mangled: `{$cgu_name}`) was not recorded")] pub(crate) struct CguNotRecorded<'a> { pub cgu_user_name: &'a str, pub cgu_name: &'a str, } #[derive(Diagnostic)] -#[diag(codegen_ssa_unknown_reuse_kind)] +#[diag("unknown cgu-reuse-kind `{$kind}` specified")] pub(crate) struct UnknownReuseKind { #[primary_span] pub span: Span, @@ -46,14 +51,16 @@ pub(crate) struct UnknownReuseKind { } #[derive(Diagnostic)] -#[diag(codegen_ssa_missing_query_depgraph)] +#[diag("found CGU-reuse attribute but `-Zquery-dep-graph` was not specified")] pub(crate) struct MissingQueryDepGraph { #[primary_span] pub span: Span, } #[derive(Diagnostic)] -#[diag(codegen_ssa_malformed_cgu_name)] +#[diag( + "found malformed codegen unit name `{$user_path}`. codegen units names must always start with the name of the crate (`{$crate_name}` in this case)." +)] pub(crate) struct MalformedCguName { #[primary_span] pub span: Span, @@ -62,7 +69,7 @@ pub(crate) struct MalformedCguName { } #[derive(Diagnostic)] -#[diag(codegen_ssa_no_module_named)] +#[diag("no module named `{$user_path}` (mangled: {$cgu_name}). available modules: {$cgu_names}")] pub(crate) struct NoModuleNamed<'a> { #[primary_span] pub span: Span, @@ -72,7 +79,7 @@ pub(crate) struct NoModuleNamed<'a> { } #[derive(Diagnostic)] -#[diag(codegen_ssa_field_associated_value_expected)] +#[diag("associated value expected for `{$name}`")] pub(crate) struct FieldAssociatedValueExpected { #[primary_span] pub span: Span, @@ -80,7 +87,7 @@ pub(crate) struct FieldAssociatedValueExpected { } #[derive(Diagnostic)] -#[diag(codegen_ssa_no_field)] +#[diag("no field `{$name}`")] pub(crate) struct NoField { #[primary_span] pub span: Span, @@ -88,56 +95,56 @@ pub(crate) struct NoField { } #[derive(Diagnostic)] -#[diag(codegen_ssa_lib_def_write_failure)] +#[diag("failed to write lib.def file: {$error}")] pub(crate) struct LibDefWriteFailure { pub error: Error, } #[derive(Diagnostic)] -#[diag(codegen_ssa_version_script_write_failure)] +#[diag("failed to write version script: {$error}")] pub(crate) struct VersionScriptWriteFailure { pub error: Error, } #[derive(Diagnostic)] -#[diag(codegen_ssa_symbol_file_write_failure)] +#[diag("failed to write symbols file: {$error}")] pub(crate) struct SymbolFileWriteFailure { pub error: Error, } #[derive(Diagnostic)] -#[diag(codegen_ssa_ld64_unimplemented_modifier)] +#[diag("`as-needed` modifier not implemented yet for ld64")] pub(crate) struct Ld64UnimplementedModifier; #[derive(Diagnostic)] -#[diag(codegen_ssa_linker_unsupported_modifier)] +#[diag("`as-needed` modifier not supported for current linker")] pub(crate) struct LinkerUnsupportedModifier; #[derive(Diagnostic)] -#[diag(codegen_ssa_L4Bender_exporting_symbols_unimplemented)] +#[diag("exporting symbols not implemented yet for L4Bender")] pub(crate) struct L4BenderExportingSymbolsUnimplemented; #[derive(Diagnostic)] -#[diag(codegen_ssa_no_natvis_directory)] +#[diag("error enumerating natvis directory: {$error}")] pub(crate) struct NoNatvisDirectory { pub error: Error, } #[derive(Diagnostic)] -#[diag(codegen_ssa_no_saved_object_file)] +#[diag("cached cgu {$cgu_name} should have an object file, but doesn't")] pub(crate) struct NoSavedObjectFile<'a> { pub cgu_name: &'a str, } #[derive(Diagnostic)] -#[diag(codegen_ssa_requires_rust_abi, code = E0737)] +#[diag("`#[track_caller]` requires Rust ABI", code = E0737)] pub(crate) struct RequiresRustAbi { #[primary_span] pub span: Span, } #[derive(Diagnostic)] -#[diag(codegen_ssa_copy_path_buf)] +#[diag("unable to copy {$source_file} to {$output_path}: {$error}")] pub(crate) struct CopyPathBuf { pub source_file: PathBuf, pub output_path: PathBuf, @@ -146,7 +153,7 @@ pub(crate) struct CopyPathBuf { // Reports Paths using `Debug` implementation rather than Path's `Display` implementation. #[derive(Diagnostic)] -#[diag(codegen_ssa_copy_path)] +#[diag("could not copy {$from} to {$to}: {$error}")] pub struct CopyPath<'a> { from: DebugArgPath<'a>, to: DebugArgPath<'a>, @@ -168,38 +175,42 @@ impl IntoDiagArg for DebugArgPath<'_> { } #[derive(Diagnostic)] -#[diag(codegen_ssa_binary_output_to_tty)] +#[diag( + "option `-o` or `--emit` is used to write binary output type `{$shorthand}` to stdout, but stdout is a tty" +)] pub struct BinaryOutputToTty { pub shorthand: &'static str, } #[derive(Diagnostic)] -#[diag(codegen_ssa_ignoring_emit_path)] +#[diag("ignoring emit path because multiple .{$extension} files were produced")] pub struct IgnoringEmitPath { pub extension: &'static str, } #[derive(Diagnostic)] -#[diag(codegen_ssa_ignoring_output)] +#[diag("ignoring -o because multiple .{$extension} files were produced")] pub struct IgnoringOutput { pub extension: &'static str, } #[derive(Diagnostic)] -#[diag(codegen_ssa_create_temp_dir)] +#[diag("couldn't create a temp dir: {$error}")] pub(crate) struct CreateTempDir { pub error: Error, } #[derive(Diagnostic)] -#[diag(codegen_ssa_add_native_library)] +#[diag("failed to add native library {$library_path}: {$error}")] pub(crate) struct AddNativeLibrary { pub library_path: PathBuf, pub error: Error, } #[derive(Diagnostic)] -#[diag(codegen_ssa_multiple_external_func_decl)] +#[diag( + "multiple declarations of external function `{$function}` from library `{$library_name}` have different calling conventions" +)] pub(crate) struct MultipleExternalFuncDecl<'a> { #[primary_span] pub span: Span, @@ -209,16 +220,18 @@ pub(crate) struct MultipleExternalFuncDecl<'a> { #[derive(Diagnostic)] pub enum LinkRlibError { - #[diag(codegen_ssa_rlib_missing_format)] + #[diag("could not find formats for rlibs")] MissingFormat, - #[diag(codegen_ssa_rlib_only_rmeta_found)] + #[diag("could not find rlib for: `{$crate_name}`, found rmeta (metadata) file")] OnlyRmetaFound { crate_name: Symbol }, - #[diag(codegen_ssa_rlib_not_found)] + #[diag("could not find rlib for: `{$crate_name}`")] NotFound { crate_name: Symbol }, - #[diag(codegen_ssa_rlib_incompatible_dependency_formats)] + #[diag( + "`{$ty1}` and `{$ty2}` do not have equivalent dependency formats (`{$list1}` vs `{$list2}`)" + )] IncompatibleDependencyFormats { ty1: String, ty2: String, list1: String, list2: String }, } @@ -228,122 +241,122 @@ impl Diagnostic<'_, G> for ThorinErrorWrapper { fn into_diag(self, dcx: DiagCtxtHandle<'_>, level: Level) -> Diag<'_, G> { let build = |msg| Diag::new(dcx, level, msg); match self.0 { - thorin::Error::ReadInput(_) => build(fluent::codegen_ssa_thorin_read_input_failure), + thorin::Error::ReadInput(_) => build(inline_fluent!("failed to read input file")), thorin::Error::ParseFileKind(_) => { - build(fluent::codegen_ssa_thorin_parse_input_file_kind) + build(inline_fluent!("failed to parse input file kind")) } thorin::Error::ParseObjectFile(_) => { - build(fluent::codegen_ssa_thorin_parse_input_object_file) + build(inline_fluent!("failed to parse input object file")) } thorin::Error::ParseArchiveFile(_) => { - build(fluent::codegen_ssa_thorin_parse_input_archive_file) + build(inline_fluent!("failed to parse input archive file")) } thorin::Error::ParseArchiveMember(_) => { - build(fluent::codegen_ssa_thorin_parse_archive_member) + build(inline_fluent!("failed to parse archive member")) } - thorin::Error::InvalidInputKind => build(fluent::codegen_ssa_thorin_invalid_input_kind), - thorin::Error::DecompressData(_) => build(fluent::codegen_ssa_thorin_decompress_data), + thorin::Error::InvalidInputKind => build(inline_fluent!("input is not an archive or elf object")), + thorin::Error::DecompressData(_) => build(inline_fluent!("failed to decompress compressed section")), thorin::Error::NamelessSection(_, offset) => { - build(fluent::codegen_ssa_thorin_section_without_name) + build(inline_fluent!("section without name at offset {$offset}")) .with_arg("offset", format!("0x{offset:08x}")) } thorin::Error::RelocationWithInvalidSymbol(section, offset) => { - build(fluent::codegen_ssa_thorin_relocation_with_invalid_symbol) + build(inline_fluent!("relocation with invalid symbol for section `{$section}` at offset {$offset}")) .with_arg("section", section) .with_arg("offset", format!("0x{offset:08x}")) } thorin::Error::MultipleRelocations(section, offset) => { - build(fluent::codegen_ssa_thorin_multiple_relocations) + build(inline_fluent!("multiple relocations for section `{$section}` at offset {$offset}")) .with_arg("section", section) .with_arg("offset", format!("0x{offset:08x}")) } thorin::Error::UnsupportedRelocation(section, offset) => { - build(fluent::codegen_ssa_thorin_unsupported_relocation) + build(inline_fluent!("unsupported relocation for section {$section} at offset {$offset}")) .with_arg("section", section) .with_arg("offset", format!("0x{offset:08x}")) } - thorin::Error::MissingDwoName(id) => build(fluent::codegen_ssa_thorin_missing_dwo_name) + thorin::Error::MissingDwoName(id) => build(inline_fluent!("missing path attribute to DWARF object ({$id})")) .with_arg("id", format!("0x{id:08x}")), thorin::Error::NoCompilationUnits => { - build(fluent::codegen_ssa_thorin_no_compilation_units) + build(inline_fluent!("input object has no compilation units")) } - thorin::Error::NoDie => build(fluent::codegen_ssa_thorin_no_die), + thorin::Error::NoDie => build(inline_fluent!("no top-level debugging information entry in compilation/type unit")), thorin::Error::TopLevelDieNotUnit => { - build(fluent::codegen_ssa_thorin_top_level_die_not_unit) + build(inline_fluent!("top-level debugging information entry is not a compilation/type unit")) } thorin::Error::MissingRequiredSection(section) => { - build(fluent::codegen_ssa_thorin_missing_required_section) + build(inline_fluent!("input object missing required section `{$section}`")) .with_arg("section", section) } thorin::Error::ParseUnitAbbreviations(_) => { - build(fluent::codegen_ssa_thorin_parse_unit_abbreviations) + build(inline_fluent!("failed to parse unit abbreviations")) } thorin::Error::ParseUnitAttribute(_) => { - build(fluent::codegen_ssa_thorin_parse_unit_attribute) + build(inline_fluent!("failed to parse unit attribute")) } thorin::Error::ParseUnitHeader(_) => { - build(fluent::codegen_ssa_thorin_parse_unit_header) + build(inline_fluent!("failed to parse unit header")) } - thorin::Error::ParseUnit(_) => build(fluent::codegen_ssa_thorin_parse_unit), + thorin::Error::ParseUnit(_) => build(inline_fluent!("failed to parse unit")), thorin::Error::IncompatibleIndexVersion(section, format, actual) => { - build(fluent::codegen_ssa_thorin_incompatible_index_version) + build(inline_fluent!("incompatible `{$section}` index version: found version {$actual}, expected version {$format}")) .with_arg("section", section) .with_arg("actual", actual) .with_arg("format", format) } thorin::Error::OffsetAtIndex(_, index) => { - build(fluent::codegen_ssa_thorin_offset_at_index).with_arg("index", index) + build(inline_fluent!("read offset at index {$index} of `.debug_str_offsets.dwo` section")).with_arg("index", index) } thorin::Error::StrAtOffset(_, offset) => { - build(fluent::codegen_ssa_thorin_str_at_offset) + build(inline_fluent!("read string at offset {$offset} of `.debug_str.dwo` section")) .with_arg("offset", format!("0x{offset:08x}")) } thorin::Error::ParseIndex(_, section) => { - build(fluent::codegen_ssa_thorin_parse_index).with_arg("section", section) + build(inline_fluent!("failed to parse `{$section}` index section")).with_arg("section", section) } thorin::Error::UnitNotInIndex(unit) => { - build(fluent::codegen_ssa_thorin_unit_not_in_index) + build(inline_fluent!("unit {$unit} from input package is not in its index")) .with_arg("unit", format!("0x{unit:08x}")) } thorin::Error::RowNotInIndex(_, row) => { - build(fluent::codegen_ssa_thorin_row_not_in_index).with_arg("row", row) + build(inline_fluent!("row {$row} found in index's hash table not present in index")).with_arg("row", row) } - thorin::Error::SectionNotInRow => build(fluent::codegen_ssa_thorin_section_not_in_row), - thorin::Error::EmptyUnit(unit) => build(fluent::codegen_ssa_thorin_empty_unit) + thorin::Error::SectionNotInRow => build(inline_fluent!("section not found in unit's row in index")), + thorin::Error::EmptyUnit(unit) => build(inline_fluent!("unit {$unit} in input DWARF object with no data")) .with_arg("unit", format!("0x{unit:08x}")), thorin::Error::MultipleDebugInfoSection => { - build(fluent::codegen_ssa_thorin_multiple_debug_info_section) + build(inline_fluent!("multiple `.debug_info.dwo` sections")) } thorin::Error::MultipleDebugTypesSection => { - build(fluent::codegen_ssa_thorin_multiple_debug_types_section) + build(inline_fluent!("multiple `.debug_types.dwo` sections in a package")) } - thorin::Error::NotSplitUnit => build(fluent::codegen_ssa_thorin_not_split_unit), - thorin::Error::DuplicateUnit(unit) => build(fluent::codegen_ssa_thorin_duplicate_unit) + thorin::Error::NotSplitUnit => build(inline_fluent!("regular compilation unit in object (missing dwo identifier)")), + thorin::Error::DuplicateUnit(unit) => build(inline_fluent!("duplicate split compilation unit ({$unit})")) .with_arg("unit", format!("0x{unit:08x}")), thorin::Error::MissingReferencedUnit(unit) => { - build(fluent::codegen_ssa_thorin_missing_referenced_unit) + build(inline_fluent!("unit {$unit} referenced by executable was not found")) .with_arg("unit", format!("0x{unit:08x}")) } thorin::Error::NoOutputObjectCreated => { - build(fluent::codegen_ssa_thorin_not_output_object_created) + build(inline_fluent!("no output object was created from inputs")) } thorin::Error::MixedInputEncodings => { - build(fluent::codegen_ssa_thorin_mixed_input_encodings) + build(inline_fluent!("input objects have mixed encodings")) } thorin::Error::Io(e) => { - build(fluent::codegen_ssa_thorin_io).with_arg("error", format!("{e}")) + build(inline_fluent!("{$error}")).with_arg("error", format!("{e}")) } thorin::Error::ObjectRead(e) => { - build(fluent::codegen_ssa_thorin_object_read).with_arg("error", format!("{e}")) + build(inline_fluent!("{$error}")).with_arg("error", format!("{e}")) } thorin::Error::ObjectWrite(e) => { - build(fluent::codegen_ssa_thorin_object_write).with_arg("error", format!("{e}")) + build(inline_fluent!("{$error}")).with_arg("error", format!("{e}")) } thorin::Error::GimliRead(e) => { - build(fluent::codegen_ssa_thorin_gimli_read).with_arg("error", format!("{e}")) + build(inline_fluent!("{$error}")).with_arg("error", format!("{e}")) } thorin::Error::GimliWrite(e) => { - build(fluent::codegen_ssa_thorin_gimli_write).with_arg("error", format!("{e}")) + build(inline_fluent!("{$error}")).with_arg("error", format!("{e}")) } _ => unimplemented!("Untranslated thorin error"), } @@ -361,7 +374,11 @@ pub(crate) struct LinkingFailed<'a> { impl Diagnostic<'_, G> for LinkingFailed<'_> { fn into_diag(mut self, dcx: DiagCtxtHandle<'_>, level: Level) -> Diag<'_, G> { - let mut diag = Diag::new(dcx, level, fluent::codegen_ssa_linking_failed); + let mut diag = Diag::new( + dcx, + level, + inline_fluent!("linking with `{$linker_path}` failed: {$exit_status}"), + ); diag.arg("linker_path", format!("{}", self.linker_path.display())); diag.arg("exit_status", format!("{}", self.exit_status)); @@ -470,11 +487,11 @@ impl Diagnostic<'_, G> for LinkingFailed<'_> { // Trying to match an error from OS linkers // which by now we have no way to translate. if contains_undefined_ref { - diag.note(fluent::codegen_ssa_extern_funcs_not_found) - .note(fluent::codegen_ssa_specify_libraries_to_link); + diag.note(inline_fluent!("some `extern` functions couldn't be found; some native libraries may need to be installed or have their path specified")) + .note(inline_fluent!("use the `-l` flag to specify native libraries to link")); if rustc_session::utils::was_invoked_from_cargo() { - diag.note(fluent::codegen_ssa_use_cargo_directive); + diag.note(inline_fluent!("use the `cargo:rustc-link-lib` directive to specify the native libraries to link with Cargo (see https://doc.rust-lang.org/cargo/reference/build-scripts.html#rustc-link-lib)")); } } diag @@ -482,7 +499,7 @@ impl Diagnostic<'_, G> for LinkingFailed<'_> { } #[derive(Diagnostic)] -#[diag(codegen_ssa_link_exe_unexpected_error)] +#[diag("`link.exe` returned an unexpected error")] pub(crate) struct LinkExeUnexpectedError; pub(crate) struct LinkExeStatusStackBufferOverrun; @@ -490,41 +507,43 @@ pub(crate) struct LinkExeStatusStackBufferOverrun; impl<'a, G: EmissionGuarantee> Diagnostic<'a, G> for LinkExeStatusStackBufferOverrun { fn into_diag(self, dcx: rustc_errors::DiagCtxtHandle<'a>, level: Level) -> Diag<'a, G> { let mut diag = - Diag::new(dcx, level, fluent::codegen_ssa_link_exe_status_stack_buffer_overrun); - diag.note(fluent::codegen_ssa_abort_note); - diag.note(fluent::codegen_ssa_event_log_note); + Diag::new(dcx, level, inline_fluent!("0xc0000409 is `STATUS_STACK_BUFFER_OVERRUN`")); + diag.note(inline_fluent!( + "this may have been caused by a program abort and not a stack buffer overrun" + )); + diag.note(inline_fluent!("consider checking the Application Event Log for Windows Error Reporting events to see the fail fast error code")); diag } } #[derive(Diagnostic)] -#[diag(codegen_ssa_repair_vs_build_tools)] +#[diag("the Visual Studio build tools may need to be repaired using the Visual Studio installer")] pub(crate) struct RepairVSBuildTools; #[derive(Diagnostic)] -#[diag(codegen_ssa_missing_cpp_build_tool_component)] +#[diag("or a necessary component may be missing from the \"C++ build tools\" workload")] pub(crate) struct MissingCppBuildToolComponent; #[derive(Diagnostic)] -#[diag(codegen_ssa_select_cpp_build_tool_workload)] +#[diag("in the Visual Studio installer, ensure the \"C++ build tools\" workload is selected")] pub(crate) struct SelectCppBuildToolWorkload; #[derive(Diagnostic)] -#[diag(codegen_ssa_visual_studio_not_installed)] +#[diag("you may need to install Visual Studio build tools with the \"C++ build tools\" workload")] pub(crate) struct VisualStudioNotInstalled; #[derive(Diagnostic)] -#[diag(codegen_ssa_linker_not_found)] -#[note] +#[diag("linker `{$linker_path}` not found")] +#[note("{$error}")] pub(crate) struct LinkerNotFound { pub linker_path: PathBuf, pub error: Error, } #[derive(Diagnostic)] -#[diag(codegen_ssa_unable_to_exe_linker)] -#[note] -#[note(codegen_ssa_command_note)] +#[diag("could not exec the linker `{$linker_path}`")] +#[note("{$error}")] +#[note("{$command_formatted}")] pub(crate) struct UnableToExeLinker { pub linker_path: PathBuf, pub error: Error, @@ -532,42 +551,46 @@ pub(crate) struct UnableToExeLinker { } #[derive(Diagnostic)] -#[diag(codegen_ssa_msvc_missing_linker)] +#[diag("the msvc targets depend on the msvc linker but `link.exe` was not found")] pub(crate) struct MsvcMissingLinker; #[derive(Diagnostic)] -#[diag(codegen_ssa_self_contained_linker_missing)] +#[diag( + "the self-contained linker was requested, but it wasn't found in the target's sysroot, or in rustc's sysroot" +)] pub(crate) struct SelfContainedLinkerMissing; #[derive(Diagnostic)] -#[diag(codegen_ssa_check_installed_visual_studio)] +#[diag( + "please ensure that Visual Studio 2017 or later, or Build Tools for Visual Studio were installed with the Visual C++ option." +)] pub(crate) struct CheckInstalledVisualStudio; #[derive(Diagnostic)] -#[diag(codegen_ssa_insufficient_vs_code_product)] +#[diag("VS Code is a different product, and is not sufficient.")] pub(crate) struct InsufficientVSCodeProduct; #[derive(Diagnostic)] -#[diag(codegen_ssa_cpu_required)] +#[diag("target requires explicitly specifying a cpu with `-C target-cpu`")] pub(crate) struct CpuRequired; #[derive(Diagnostic)] -#[diag(codegen_ssa_processing_dymutil_failed)] -#[note] +#[diag("processing debug info with `dsymutil` failed: {$status}")] +#[note("{$output}")] pub(crate) struct ProcessingDymutilFailed { pub status: ExitStatus, pub output: String, } #[derive(Diagnostic)] -#[diag(codegen_ssa_unable_to_run_dsymutil)] +#[diag("unable to run `dsymutil`: {$error}")] pub(crate) struct UnableToRunDsymutil { pub error: Error, } #[derive(Diagnostic)] -#[diag(codegen_ssa_stripping_debug_info_failed)] -#[note] +#[diag("stripping debug info with `{$util}` failed: {$status}")] +#[note("{$output}")] pub(crate) struct StrippingDebugInfoFailed<'a> { pub util: &'a str, pub status: ExitStatus, @@ -575,53 +598,57 @@ pub(crate) struct StrippingDebugInfoFailed<'a> { } #[derive(Diagnostic)] -#[diag(codegen_ssa_unable_to_run)] +#[diag("unable to run `{$util}`: {$error}")] pub(crate) struct UnableToRun<'a> { pub util: &'a str, pub error: Error, } #[derive(Diagnostic)] -#[diag(codegen_ssa_linker_file_stem)] +#[diag("couldn't extract file stem from specified linker")] pub(crate) struct LinkerFileStem; #[derive(Diagnostic)] -#[diag(codegen_ssa_static_library_native_artifacts)] +#[diag( + "link against the following native artifacts when linking against this static library. The order and any duplication can be significant on some platforms." +)] pub(crate) struct StaticLibraryNativeArtifacts; #[derive(Diagnostic)] -#[diag(codegen_ssa_static_library_native_artifacts_to_file)] +#[diag( + "native artifacts to link against have been written to {$path}. The order and any duplication can be significant on some platforms." +)] pub(crate) struct StaticLibraryNativeArtifactsToFile<'a> { pub path: &'a Path, } #[derive(Diagnostic)] -#[diag(codegen_ssa_link_script_unavailable)] +#[diag("can only use link script when linking with GNU-like linker")] pub(crate) struct LinkScriptUnavailable; #[derive(Diagnostic)] -#[diag(codegen_ssa_link_script_write_failure)] +#[diag("failed to write link script to {$path}: {$error}")] pub(crate) struct LinkScriptWriteFailure { pub path: PathBuf, pub error: Error, } #[derive(Diagnostic)] -#[diag(codegen_ssa_failed_to_write)] +#[diag("failed to write {$path}: {$error}")] pub(crate) struct FailedToWrite { pub path: PathBuf, pub error: Error, } #[derive(Diagnostic)] -#[diag(codegen_ssa_unable_to_write_debugger_visualizer)] +#[diag("unable to write debugger visualizer file `{$path}`: {$error}")] pub(crate) struct UnableToWriteDebuggerVisualizer { pub path: PathBuf, pub error: Error, } #[derive(Diagnostic)] -#[diag(codegen_ssa_rlib_archive_build_failure)] +#[diag("failed to build archive from rlib at `{$path}`: {$error}")] pub(crate) struct RlibArchiveBuildFailure { pub path: PathBuf, pub error: Error, @@ -630,68 +657,70 @@ pub(crate) struct RlibArchiveBuildFailure { #[derive(Diagnostic)] // Public for ArchiveBuilderBuilder::extract_bundled_libs pub enum ExtractBundledLibsError<'a> { - #[diag(codegen_ssa_extract_bundled_libs_open_file)] + #[diag("failed to open file '{$rlib}': {$error}")] OpenFile { rlib: &'a Path, error: Box }, - #[diag(codegen_ssa_extract_bundled_libs_mmap_file)] + #[diag("failed to mmap file '{$rlib}': {$error}")] MmapFile { rlib: &'a Path, error: Box }, - #[diag(codegen_ssa_extract_bundled_libs_parse_archive)] + #[diag("failed to parse archive '{$rlib}': {$error}")] ParseArchive { rlib: &'a Path, error: Box }, - #[diag(codegen_ssa_extract_bundled_libs_read_entry)] + #[diag("failed to read entry '{$rlib}': {$error}")] ReadEntry { rlib: &'a Path, error: Box }, - #[diag(codegen_ssa_extract_bundled_libs_archive_member)] + #[diag("failed to get data from archive member '{$rlib}': {$error}")] ArchiveMember { rlib: &'a Path, error: Box }, - #[diag(codegen_ssa_extract_bundled_libs_convert_name)] + #[diag("failed to convert name '{$rlib}': {$error}")] ConvertName { rlib: &'a Path, error: Box }, - #[diag(codegen_ssa_extract_bundled_libs_write_file)] + #[diag("failed to write file '{$rlib}': {$error}")] WriteFile { rlib: &'a Path, error: Box }, - #[diag(codegen_ssa_extract_bundled_libs_write_file)] + #[diag("failed to write file '{$rlib}': {$error}")] ExtractSection { rlib: &'a Path, error: Box }, } #[derive(Diagnostic)] -#[diag(codegen_ssa_read_file)] +#[diag("failed to read file: {$message}")] pub(crate) struct ReadFileError { pub message: std::io::Error, } #[derive(Diagnostic)] -#[diag(codegen_ssa_unsupported_link_self_contained)] +#[diag("option `-C link-self-contained` is not supported on this target")] pub(crate) struct UnsupportedLinkSelfContained; #[derive(Diagnostic)] -#[diag(codegen_ssa_archive_build_failure)] +#[diag("failed to build archive at `{$path}`: {$error}")] pub(crate) struct ArchiveBuildFailure { pub path: PathBuf, pub error: std::io::Error, } #[derive(Diagnostic)] -#[diag(codegen_ssa_unknown_archive_kind)] +#[diag("don't know how to build archive of type: {$kind}")] pub(crate) struct UnknownArchiveKind<'a> { pub kind: &'a str, } #[derive(Diagnostic)] -#[diag(codegen_ssa_bpf_staticlib_not_supported)] +#[diag("linking static libraries is not supported for BPF")] pub(crate) struct BpfStaticlibNotSupported; #[derive(Diagnostic)] -#[diag(codegen_ssa_multiple_main_functions)] -#[help] +#[diag("entry symbol `main` declared multiple times")] +#[help( + "did you use `#[no_mangle]` on `fn main`? Use `#![no_main]` to suppress the usual Rust-generated entry point" +)] pub(crate) struct MultipleMainFunctions { #[primary_span] pub span: Span, } #[derive(Diagnostic)] -#[diag(codegen_ssa_shuffle_indices_evaluation)] +#[diag("could not evaluate shuffle_indices at compile time")] pub(crate) struct ShuffleIndicesEvaluation { #[primary_span] pub span: Span, @@ -699,7 +728,7 @@ pub(crate) struct ShuffleIndicesEvaluation { #[derive(Diagnostic)] pub enum InvalidMonomorphization<'tcx> { - #[diag(codegen_ssa_invalid_monomorphization_basic_integer_type, code = E0511)] + #[diag("invalid monomorphization of `{$name}` intrinsic: expected basic integer type, found `{$ty}`", code = E0511)] BasicIntegerType { #[primary_span] span: Span, @@ -707,7 +736,7 @@ pub enum InvalidMonomorphization<'tcx> { ty: Ty<'tcx>, }, - #[diag(codegen_ssa_invalid_monomorphization_basic_integer_or_ptr_type, code = E0511)] + #[diag("invalid monomorphization of `{$name}` intrinsic: expected basic integer or pointer type, found `{$ty}`", code = E0511)] BasicIntegerOrPtrType { #[primary_span] span: Span, @@ -715,7 +744,7 @@ pub enum InvalidMonomorphization<'tcx> { ty: Ty<'tcx>, }, - #[diag(codegen_ssa_invalid_monomorphization_basic_float_type, code = E0511)] + #[diag("invalid monomorphization of `{$name}` intrinsic: expected basic float type, found `{$ty}`", code = E0511)] BasicFloatType { #[primary_span] span: Span, @@ -723,14 +752,14 @@ pub enum InvalidMonomorphization<'tcx> { ty: Ty<'tcx>, }, - #[diag(codegen_ssa_invalid_monomorphization_float_to_int_unchecked, code = E0511)] + #[diag("invalid monomorphization of `float_to_int_unchecked` intrinsic: expected basic float type, found `{$ty}`", code = E0511)] FloatToIntUnchecked { #[primary_span] span: Span, ty: Ty<'tcx>, }, - #[diag(codegen_ssa_invalid_monomorphization_floating_point_vector, code = E0511)] + #[diag("invalid monomorphization of `{$name}` intrinsic: unsupported element type `{$f_ty}` of floating-point vector `{$in_ty}`", code = E0511)] FloatingPointVector { #[primary_span] span: Span, @@ -739,7 +768,7 @@ pub enum InvalidMonomorphization<'tcx> { in_ty: Ty<'tcx>, }, - #[diag(codegen_ssa_invalid_monomorphization_floating_point_type, code = E0511)] + #[diag("invalid monomorphization of `{$name}` intrinsic: `{$in_ty}` is not a floating-point type", code = E0511)] FloatingPointType { #[primary_span] span: Span, @@ -747,14 +776,14 @@ pub enum InvalidMonomorphization<'tcx> { in_ty: Ty<'tcx>, }, - #[diag(codegen_ssa_invalid_monomorphization_unrecognized_intrinsic, code = E0511)] + #[diag("invalid monomorphization of `{$name}` intrinsic: unrecognized intrinsic `{$name}`", code = E0511)] UnrecognizedIntrinsic { #[primary_span] span: Span, name: Symbol, }, - #[diag(codegen_ssa_invalid_monomorphization_simd_argument, code = E0511)] + #[diag("invalid monomorphization of `{$name}` intrinsic: expected SIMD argument type, found non-SIMD `{$ty}`", code = E0511)] SimdArgument { #[primary_span] span: Span, @@ -762,7 +791,7 @@ pub enum InvalidMonomorphization<'tcx> { ty: Ty<'tcx>, }, - #[diag(codegen_ssa_invalid_monomorphization_simd_input, code = E0511)] + #[diag("invalid monomorphization of `{$name}` intrinsic: expected SIMD input type, found non-SIMD `{$ty}`", code = E0511)] SimdInput { #[primary_span] span: Span, @@ -770,7 +799,7 @@ pub enum InvalidMonomorphization<'tcx> { ty: Ty<'tcx>, }, - #[diag(codegen_ssa_invalid_monomorphization_simd_first, code = E0511)] + #[diag("invalid monomorphization of `{$name}` intrinsic: expected SIMD first type, found non-SIMD `{$ty}`", code = E0511)] SimdFirst { #[primary_span] span: Span, @@ -778,7 +807,7 @@ pub enum InvalidMonomorphization<'tcx> { ty: Ty<'tcx>, }, - #[diag(codegen_ssa_invalid_monomorphization_simd_second, code = E0511)] + #[diag("invalid monomorphization of `{$name}` intrinsic: expected SIMD second type, found non-SIMD `{$ty}`", code = E0511)] SimdSecond { #[primary_span] span: Span, @@ -786,7 +815,7 @@ pub enum InvalidMonomorphization<'tcx> { ty: Ty<'tcx>, }, - #[diag(codegen_ssa_invalid_monomorphization_simd_third, code = E0511)] + #[diag("invalid monomorphization of `{$name}` intrinsic: expected SIMD third type, found non-SIMD `{$ty}`", code = E0511)] SimdThird { #[primary_span] span: Span, @@ -794,7 +823,7 @@ pub enum InvalidMonomorphization<'tcx> { ty: Ty<'tcx>, }, - #[diag(codegen_ssa_invalid_monomorphization_simd_return, code = E0511)] + #[diag("invalid monomorphization of `{$name}` intrinsic: expected SIMD return type, found non-SIMD `{$ty}`", code = E0511)] SimdReturn { #[primary_span] span: Span, @@ -802,7 +831,7 @@ pub enum InvalidMonomorphization<'tcx> { ty: Ty<'tcx>, }, - #[diag(codegen_ssa_invalid_monomorphization_invalid_bitmask, code = E0511)] + #[diag("invalid monomorphization of `{$name}` intrinsic: invalid bitmask `{$mask_ty}`, expected `u{$expected_int_bits}` or `[u8; {$expected_bytes}]`", code = E0511)] InvalidBitmask { #[primary_span] span: Span, @@ -812,7 +841,7 @@ pub enum InvalidMonomorphization<'tcx> { expected_bytes: u64, }, - #[diag(codegen_ssa_invalid_monomorphization_return_length_input_type, code = E0511)] + #[diag("invalid monomorphization of `{$name}` intrinsic: expected return type with length {$in_len} (same as input type `{$in_ty}`), found `{$ret_ty}` with length {$out_len}", code = E0511)] ReturnLengthInputType { #[primary_span] span: Span, @@ -823,7 +852,7 @@ pub enum InvalidMonomorphization<'tcx> { out_len: u64, }, - #[diag(codegen_ssa_invalid_monomorphization_second_argument_length, code = E0511)] + #[diag("invalid monomorphization of `{$name}` intrinsic: expected second argument with length {$in_len} (same as input type `{$in_ty}`), found `{$arg_ty}` with length {$out_len}", code = E0511)] SecondArgumentLength { #[primary_span] span: Span, @@ -834,7 +863,7 @@ pub enum InvalidMonomorphization<'tcx> { out_len: u64, }, - #[diag(codegen_ssa_invalid_monomorphization_third_argument_length, code = E0511)] + #[diag("invalid monomorphization of `{$name}` intrinsic: expected third argument with length {$in_len} (same as input type `{$in_ty}`), found `{$arg_ty}` with length {$out_len}", code = E0511)] ThirdArgumentLength { #[primary_span] span: Span, @@ -845,7 +874,7 @@ pub enum InvalidMonomorphization<'tcx> { out_len: u64, }, - #[diag(codegen_ssa_invalid_monomorphization_return_integer_type, code = E0511)] + #[diag("invalid monomorphization of `{$name}` intrinsic: expected return type with integer elements, found `{$ret_ty}` with non-integer `{$out_ty}`", code = E0511)] ReturnIntegerType { #[primary_span] span: Span, @@ -854,7 +883,7 @@ pub enum InvalidMonomorphization<'tcx> { out_ty: Ty<'tcx>, }, - #[diag(codegen_ssa_invalid_monomorphization_simd_shuffle, code = E0511)] + #[diag("invalid monomorphization of `{$name}` intrinsic: simd_shuffle index must be a SIMD vector of `u32`, got `{$ty}`", code = E0511)] SimdShuffle { #[primary_span] span: Span, @@ -862,7 +891,7 @@ pub enum InvalidMonomorphization<'tcx> { ty: Ty<'tcx>, }, - #[diag(codegen_ssa_invalid_monomorphization_return_length, code = E0511)] + #[diag("invalid monomorphization of `{$name}` intrinsic: expected return type of length {$in_len}, found `{$ret_ty}` with length {$out_len}", code = E0511)] ReturnLength { #[primary_span] span: Span, @@ -872,7 +901,7 @@ pub enum InvalidMonomorphization<'tcx> { out_len: u64, }, - #[diag(codegen_ssa_invalid_monomorphization_return_element, code = E0511)] + #[diag("invalid monomorphization of `{$name}` intrinsic: expected return element type `{$in_elem}` (element of input `{$in_ty}`), found `{$ret_ty}` with element type `{$out_ty}`", code = E0511)] ReturnElement { #[primary_span] span: Span, @@ -883,7 +912,7 @@ pub enum InvalidMonomorphization<'tcx> { out_ty: Ty<'tcx>, }, - #[diag(codegen_ssa_invalid_monomorphization_simd_index_out_of_bounds, code = E0511)] + #[diag("invalid monomorphization of `{$name}` intrinsic: SIMD index #{$arg_idx} is out of bounds (limit {$total_len})", code = E0511)] SimdIndexOutOfBounds { #[primary_span] span: Span, @@ -892,7 +921,7 @@ pub enum InvalidMonomorphization<'tcx> { total_len: u128, }, - #[diag(codegen_ssa_invalid_monomorphization_inserted_type, code = E0511)] + #[diag("invalid monomorphization of `{$name}` intrinsic: expected inserted type `{$in_elem}` (element of input `{$in_ty}`), found `{$out_ty}`", code = E0511)] InsertedType { #[primary_span] span: Span, @@ -902,7 +931,7 @@ pub enum InvalidMonomorphization<'tcx> { out_ty: Ty<'tcx>, }, - #[diag(codegen_ssa_invalid_monomorphization_return_type, code = E0511)] + #[diag("invalid monomorphization of `{$name}` intrinsic: expected return type `{$in_elem}` (element of input `{$in_ty}`), found `{$ret_ty}`", code = E0511)] ReturnType { #[primary_span] span: Span, @@ -912,7 +941,7 @@ pub enum InvalidMonomorphization<'tcx> { ret_ty: Ty<'tcx>, }, - #[diag(codegen_ssa_invalid_monomorphization_expected_return_type, code = E0511)] + #[diag("invalid monomorphization of `{$name}` intrinsic: expected return type `{$in_ty}`, found `{$ret_ty}`", code = E0511)] ExpectedReturnType { #[primary_span] span: Span, @@ -921,7 +950,7 @@ pub enum InvalidMonomorphization<'tcx> { ret_ty: Ty<'tcx>, }, - #[diag(codegen_ssa_invalid_monomorphization_mismatched_lengths, code = E0511)] + #[diag("invalid monomorphization of `{$name}` intrinsic: mismatched lengths: mask length `{$m_len}` != other vector length `{$v_len}`", code = E0511)] MismatchedLengths { #[primary_span] span: Span, @@ -930,7 +959,7 @@ pub enum InvalidMonomorphization<'tcx> { v_len: u64, }, - #[diag(codegen_ssa_invalid_monomorphization_mask_wrong_element_type, code = E0511)] + #[diag("invalid monomorphization of `{$name}` intrinsic: expected mask element type to be an integer, found `{$ty}`", code = E0511)] MaskWrongElementType { #[primary_span] span: Span, @@ -938,7 +967,7 @@ pub enum InvalidMonomorphization<'tcx> { ty: Ty<'tcx>, }, - #[diag(codegen_ssa_invalid_monomorphization_cannot_return, code = E0511)] + #[diag("invalid monomorphization of `{$name}` intrinsic: cannot return `{$ret_ty}`, expected `u{$expected_int_bits}` or `[u8; {$expected_bytes}]`", code = E0511)] CannotReturn { #[primary_span] span: Span, @@ -948,7 +977,7 @@ pub enum InvalidMonomorphization<'tcx> { expected_bytes: u64, }, - #[diag(codegen_ssa_invalid_monomorphization_expected_element_type, code = E0511)] + #[diag("invalid monomorphization of `{$name}` intrinsic: expected element type `{$expected_element}` of second argument `{$second_arg}` to be a pointer to the element type `{$in_elem}` of the first argument `{$in_ty}`, found `{$expected_element}` != `{$mutability} {$in_elem}`", code = E0511)] ExpectedElementType { #[primary_span] span: Span, @@ -960,7 +989,7 @@ pub enum InvalidMonomorphization<'tcx> { mutability: ExpectedPointerMutability, }, - #[diag(codegen_ssa_invalid_monomorphization_unsupported_symbol_of_size, code = E0511)] + #[diag("invalid monomorphization of `{$name}` intrinsic: unsupported {$symbol} from `{$in_ty}` with element `{$in_elem}` of size `{$size}` to `{$ret_ty}`", code = E0511)] UnsupportedSymbolOfSize { #[primary_span] span: Span, @@ -972,7 +1001,7 @@ pub enum InvalidMonomorphization<'tcx> { ret_ty: Ty<'tcx>, }, - #[diag(codegen_ssa_invalid_monomorphization_unsupported_symbol, code = E0511)] + #[diag("invalid monomorphization of `{$name}` intrinsic: unsupported {$symbol} from `{$in_ty}` with element `{$in_elem}` to `{$ret_ty}`", code = E0511)] UnsupportedSymbol { #[primary_span] span: Span, @@ -983,7 +1012,7 @@ pub enum InvalidMonomorphization<'tcx> { ret_ty: Ty<'tcx>, }, - #[diag(codegen_ssa_invalid_monomorphization_cast_wide_pointer, code = E0511)] + #[diag("invalid monomorphization of `{$name}` intrinsic: cannot cast wide pointer `{$ty}`", code = E0511)] CastWidePointer { #[primary_span] span: Span, @@ -991,7 +1020,7 @@ pub enum InvalidMonomorphization<'tcx> { ty: Ty<'tcx>, }, - #[diag(codegen_ssa_invalid_monomorphization_expected_pointer, code = E0511)] + #[diag("invalid monomorphization of `{$name}` intrinsic: expected pointer, got `{$ty}`", code = E0511)] ExpectedPointer { #[primary_span] span: Span, @@ -999,7 +1028,7 @@ pub enum InvalidMonomorphization<'tcx> { ty: Ty<'tcx>, }, - #[diag(codegen_ssa_invalid_monomorphization_expected_usize, code = E0511)] + #[diag("invalid monomorphization of `{$name}` intrinsic: expected `usize`, got `{$ty}`", code = E0511)] ExpectedUsize { #[primary_span] span: Span, @@ -1007,7 +1036,7 @@ pub enum InvalidMonomorphization<'tcx> { ty: Ty<'tcx>, }, - #[diag(codegen_ssa_invalid_monomorphization_unsupported_cast, code = E0511)] + #[diag("invalid monomorphization of `{$name}` intrinsic: unsupported cast from `{$in_ty}` with element `{$in_elem}` to `{$ret_ty}` with element `{$out_elem}`", code = E0511)] UnsupportedCast { #[primary_span] span: Span, @@ -1018,7 +1047,7 @@ pub enum InvalidMonomorphization<'tcx> { out_elem: Ty<'tcx>, }, - #[diag(codegen_ssa_invalid_monomorphization_unsupported_operation, code = E0511)] + #[diag("invalid monomorphization of `{$name}` intrinsic: unsupported operation on `{$in_ty}` with element `{$in_elem}`", code = E0511)] UnsupportedOperation { #[primary_span] span: Span, @@ -1027,7 +1056,7 @@ pub enum InvalidMonomorphization<'tcx> { in_elem: Ty<'tcx>, }, - #[diag(codegen_ssa_invalid_monomorphization_expected_vector_element_type, code = E0511)] + #[diag("invalid monomorphization of `{$name}` intrinsic: expected element type `{$expected_element}` of vector type `{$vector_type}` to be a signed or unsigned integer type", code = E0511)] ExpectedVectorElementType { #[primary_span] span: Span, @@ -1036,7 +1065,7 @@ pub enum InvalidMonomorphization<'tcx> { vector_type: Ty<'tcx>, }, - #[diag(codegen_ssa_invalid_monomorphization_non_scalable_type, code = E0511)] + #[diag("invalid monomorphization of `{$name}` intrinsic: expected non-scalable type, found scalable type `{$ty}`", code = E0511)] NonScalableType { #[primary_span] span: Span, @@ -1060,17 +1089,17 @@ impl IntoDiagArg for ExpectedPointerMutability { } #[derive(Diagnostic)] -#[diag(codegen_ssa_target_feature_safe_trait)] +#[diag("`#[target_feature(..)]` cannot be applied to safe trait method")] pub(crate) struct TargetFeatureSafeTrait { #[primary_span] - #[label] + #[label("cannot be applied to safe trait method")] pub span: Span, - #[label(codegen_ssa_label_def)] + #[label("not an `unsafe` function")] pub def: Span, } #[derive(Diagnostic)] -#[diag(codegen_ssa_forbidden_target_feature_attr)] +#[diag("target feature `{$feature}` cannot be enabled with `#[target_feature]`: {$reason}")] pub struct ForbiddenTargetFeatureAttr<'a> { #[primary_span] pub span: Span, @@ -1079,7 +1108,7 @@ pub struct ForbiddenTargetFeatureAttr<'a> { } #[derive(Diagnostic)] -#[diag(codegen_ssa_failed_to_get_layout)] +#[diag("failed to get layout for {$ty}: {$err}")] pub struct FailedToGetLayout<'tcx> { #[primary_span] pub span: Span, @@ -1088,7 +1117,11 @@ pub struct FailedToGetLayout<'tcx> { } #[derive(Diagnostic)] -#[diag(codegen_ssa_dlltool_fail_import_library)] +#[diag( + "dlltool could not create import library with {$dlltool_path} {$dlltool_args}: +{$stdout} +{$stderr}" +)] pub(crate) struct DlltoolFailImportLibrary<'a> { pub dlltool_path: Cow<'a, str>, pub dlltool_args: String, @@ -1097,26 +1130,28 @@ pub(crate) struct DlltoolFailImportLibrary<'a> { } #[derive(Diagnostic)] -#[diag(codegen_ssa_error_writing_def_file)] +#[diag("error writing .DEF file: {$error}")] pub(crate) struct ErrorWritingDEFFile { pub error: std::io::Error, } #[derive(Diagnostic)] -#[diag(codegen_ssa_error_calling_dlltool)] +#[diag("error calling dlltool '{$dlltool_path}': {$error}")] pub(crate) struct ErrorCallingDllTool<'a> { pub dlltool_path: Cow<'a, str>, pub error: std::io::Error, } #[derive(Diagnostic)] -#[diag(codegen_ssa_error_creating_remark_dir)] +#[diag("failed to create remark directory: {$error}")] pub(crate) struct ErrorCreatingRemarkDir { pub error: std::io::Error, } #[derive(Diagnostic)] -#[diag(codegen_ssa_compiler_builtins_cannot_call)] +#[diag( + "`compiler_builtins` cannot call functions through upstream monomorphizations; encountered invalid call from `{$caller}` to `{$callee}`" +)] pub struct CompilerBuiltinsCannotCall { pub caller: String, pub callee: String, @@ -1125,23 +1160,23 @@ pub struct CompilerBuiltinsCannotCall { } #[derive(Diagnostic)] -#[diag(codegen_ssa_error_creating_import_library)] +#[diag("error creating import library for {$lib_name}: {$error}")] pub(crate) struct ErrorCreatingImportLibrary<'a> { pub lib_name: &'a str, pub error: String, } #[derive(Diagnostic)] -#[diag(codegen_ssa_aix_strip_not_used)] +#[diag("using host's `strip` binary to cross-compile to AIX which is not guaranteed to work")] pub(crate) struct AixStripNotUsed; #[derive(Diagnostic, Debug)] pub(crate) enum XcrunError { - #[diag(codegen_ssa_xcrun_failed_invoking)] + #[diag("invoking `{$command_formatted}` to find {$sdk_name}.sdk failed: {$error}")] FailedInvoking { sdk_name: &'static str, command_formatted: String, error: std::io::Error }, - #[diag(codegen_ssa_xcrun_unsuccessful)] - #[note] + #[diag("failed running `{$command_formatted}` to find {$sdk_name}.sdk")] + #[note("{$stdout}{$stderr}")] Unsuccessful { sdk_name: &'static str, command_formatted: String, @@ -1151,35 +1186,37 @@ pub(crate) enum XcrunError { } #[derive(Diagnostic, Debug)] -#[diag(codegen_ssa_xcrun_sdk_path_warning)] -#[note] +#[diag("output of `xcrun` while finding {$sdk_name}.sdk")] +#[note("{$stderr}")] pub(crate) struct XcrunSdkPathWarning { pub sdk_name: &'static str, pub stderr: String, } #[derive(LintDiagnostic)] -#[diag(codegen_ssa_aarch64_softfloat_neon)] +#[diag("enabling the `neon` target feature on the current target is unsound due to ABI issues")] pub(crate) struct Aarch64SoftfloatNeon; #[derive(Diagnostic)] -#[diag(codegen_ssa_unknown_ctarget_feature_prefix)] -#[note] +#[diag("unknown feature specified for `-Ctarget-feature`: `{$feature}`")] +#[note("features must begin with a `+` to enable or `-` to disable it")] pub(crate) struct UnknownCTargetFeaturePrefix<'a> { pub feature: &'a str, } #[derive(Subdiagnostic)] pub(crate) enum PossibleFeature<'a> { - #[help(codegen_ssa_possible_feature)] + #[help("you might have meant: `{$rust_feature}`")] Some { rust_feature: &'a str }, - #[help(codegen_ssa_consider_filing_feature_request)] + #[help("consider filing a feature request")] None, } #[derive(Diagnostic)] -#[diag(codegen_ssa_unknown_ctarget_feature)] -#[note] +#[diag("unknown and unstable feature specified for `-Ctarget-feature`: `{$feature}`")] +#[note( + "it is still passed through to the codegen backend, but use of this feature might be unsound and the behavior of this feature can change in the future" +)] pub(crate) struct UnknownCTargetFeature<'a> { pub feature: &'a str, #[subdiagnostic] @@ -1187,16 +1224,18 @@ pub(crate) struct UnknownCTargetFeature<'a> { } #[derive(Diagnostic)] -#[diag(codegen_ssa_unstable_ctarget_feature)] -#[note] +#[diag("unstable feature specified for `-Ctarget-feature`: `{$feature}`")] +#[note("this feature is not stably supported; its behavior can change in the future")] pub(crate) struct UnstableCTargetFeature<'a> { pub feature: &'a str, } #[derive(Diagnostic)] -#[diag(codegen_ssa_forbidden_ctarget_feature)] -#[note] -#[note(codegen_ssa_forbidden_ctarget_feature_issue)] +#[diag("target feature `{$feature}` cannot be {$enabled} with `-Ctarget-feature`: {$reason}")] +#[note( + "this was previously accepted by the compiler but is being phased out; it will become a hard error in a future release!" +)] +#[note("for more information, see issue #116344 ")] pub(crate) struct ForbiddenCTargetFeature<'a> { pub feature: &'a str, pub enabled: &'a str, @@ -1210,12 +1249,18 @@ pub struct TargetFeatureDisableOrEnable<'a> { } #[derive(Subdiagnostic)] -#[help(codegen_ssa_missing_features)] +#[help("add the missing features in a `target_feature` attribute")] pub struct MissingFeatures; impl Diagnostic<'_, G> for TargetFeatureDisableOrEnable<'_> { fn into_diag(self, dcx: DiagCtxtHandle<'_>, level: Level) -> Diag<'_, G> { - let mut diag = Diag::new(dcx, level, fluent::codegen_ssa_target_feature_disable_or_enable); + let mut diag = Diag::new( + dcx, + level, + inline_fluent!( + "the target features {$features} must all be either enabled or disabled together" + ), + ); if let Some(span) = self.span { diag.span(span); }; @@ -1228,29 +1273,29 @@ impl Diagnostic<'_, G> for TargetFeatureDisableOrEnable<'_ } #[derive(Diagnostic)] -#[diag(codegen_ssa_feature_not_valid)] +#[diag("the feature named `{$feature}` is not valid for this target")] pub(crate) struct FeatureNotValid<'a> { pub feature: &'a str, #[primary_span] - #[label] + #[label("`{$feature}` is not valid for this target")] pub span: Span, - #[help] + #[help("consider removing the leading `+` in the feature name")] pub plus_hint: bool, } #[derive(Diagnostic)] -#[diag(codegen_ssa_lto_disallowed)] +#[diag("lto can only be run for executables, cdylibs and static library outputs")] pub(crate) struct LtoDisallowed; #[derive(Diagnostic)] -#[diag(codegen_ssa_lto_dylib)] +#[diag("lto cannot be used for `dylib` crate type without `-Zdylib-lto`")] pub(crate) struct LtoDylib; #[derive(Diagnostic)] -#[diag(codegen_ssa_lto_proc_macro)] +#[diag("lto cannot be used for `proc-macro` crate type without `-Zdylib-lto`")] pub(crate) struct LtoProcMacro; #[derive(Diagnostic)] -#[diag(codegen_ssa_dynamic_linking_with_lto)] -#[note] +#[diag("cannot prefer dynamic linking when performing LTO")] +#[note("only 'staticlib', 'bin', and 'cdylib' outputs are supported with LTO")] pub(crate) struct DynamicLinkingWithLTO; diff --git a/compiler/rustc_codegen_ssa/src/lib.rs b/compiler/rustc_codegen_ssa/src/lib.rs index 5cca916c17b6d..e3934065b0f7f 100644 --- a/compiler/rustc_codegen_ssa/src/lib.rs +++ b/compiler/rustc_codegen_ssa/src/lib.rs @@ -55,8 +55,6 @@ pub mod size_of_val; pub mod target_features; pub mod traits; -rustc_fluent_macro::fluent_messages! { "../messages.ftl" } - pub struct ModuleCodegen { /// The name of the module. When the crate may be saved between /// compilations, incremental compilation requires that name be diff --git a/compiler/rustc_data_structures/src/profiling.rs b/compiler/rustc_data_structures/src/profiling.rs index 4a9551a60cf94..b04caa69adfbc 100644 --- a/compiler/rustc_data_structures/src/profiling.rs +++ b/compiler/rustc_data_structures/src/profiling.rs @@ -995,12 +995,14 @@ cfg_select! { } unix => { pub fn get_resident_set_size() -> Option { + use libc::{sysconf, _SC_PAGESIZE}; let field = 1; let contents = fs::read("/proc/self/statm").ok()?; let contents = String::from_utf8(contents).ok()?; let s = contents.split_whitespace().nth(field)?; let npages = s.parse::().ok()?; - Some(npages * 4096) + // SAFETY: `sysconf(_SC_PAGESIZE)` has no side effects and is safe to call. + Some(npages * unsafe { sysconf(_SC_PAGESIZE) } as usize) } } _ => { diff --git a/compiler/rustc_driver_impl/Cargo.toml b/compiler/rustc_driver_impl/Cargo.toml index cae2e3b066eeb..c24a4ca532194 100644 --- a/compiler/rustc_driver_impl/Cargo.toml +++ b/compiler/rustc_driver_impl/Cargo.toml @@ -9,7 +9,6 @@ anstyle = "1.0.13" jiff = { version = "0.2.5", default-features = false, features = ["std"] } rustc_abi = { path = "../rustc_abi" } rustc_ast = { path = "../rustc_ast" } -rustc_ast_lowering = { path = "../rustc_ast_lowering" } rustc_ast_passes = { path = "../rustc_ast_passes" } rustc_ast_pretty = { path = "../rustc_ast_pretty" } rustc_borrowck = { path = "../rustc_borrowck" } @@ -22,7 +21,6 @@ rustc_expand = { path = "../rustc_expand" } rustc_feature = { path = "../rustc_feature" } rustc_hir_analysis = { path = "../rustc_hir_analysis" } rustc_hir_pretty = { path = "../rustc_hir_pretty" } -rustc_hir_typeck = { path = "../rustc_hir_typeck" } rustc_index = { path = "../rustc_index" } rustc_interface = { path = "../rustc_interface" } rustc_lexer = { path = "../rustc_lexer" } diff --git a/compiler/rustc_driver_impl/src/lib.rs b/compiler/rustc_driver_impl/src/lib.rs index 3b9ca5ff7288c..02298dbf82670 100644 --- a/compiler/rustc_driver_impl/src/lib.rs +++ b/compiler/rustc_driver_impl/src/lib.rs @@ -20,7 +20,7 @@ use std::fs::{self, File}; use std::io::{self, IsTerminal, Read, Write}; use std::panic::{self, PanicHookInfo}; use std::path::{Path, PathBuf}; -use std::process::{self, Command, Stdio}; +use std::process::{Command, ExitCode, Stdio, Termination}; use std::sync::OnceLock; use std::sync::atomic::{AtomicBool, Ordering}; use std::time::Instant; @@ -114,25 +114,18 @@ pub fn default_translator() -> Translator { pub static DEFAULT_LOCALE_RESOURCES: &[&str] = &[ // tidy-alphabetical-start - rustc_ast_lowering::DEFAULT_LOCALE_RESOURCE, rustc_ast_passes::DEFAULT_LOCALE_RESOURCE, rustc_borrowck::DEFAULT_LOCALE_RESOURCE, rustc_builtin_macros::DEFAULT_LOCALE_RESOURCE, - rustc_codegen_ssa::DEFAULT_LOCALE_RESOURCE, rustc_const_eval::DEFAULT_LOCALE_RESOURCE, rustc_errors::DEFAULT_LOCALE_RESOURCE, - rustc_expand::DEFAULT_LOCALE_RESOURCE, rustc_hir_analysis::DEFAULT_LOCALE_RESOURCE, - rustc_hir_typeck::DEFAULT_LOCALE_RESOURCE, rustc_lint::DEFAULT_LOCALE_RESOURCE, - rustc_metadata::DEFAULT_LOCALE_RESOURCE, rustc_middle::DEFAULT_LOCALE_RESOURCE, rustc_mir_build::DEFAULT_LOCALE_RESOURCE, - rustc_mir_transform::DEFAULT_LOCALE_RESOURCE, rustc_parse::DEFAULT_LOCALE_RESOURCE, rustc_passes::DEFAULT_LOCALE_RESOURCE, rustc_pattern_analysis::DEFAULT_LOCALE_RESOURCE, - rustc_resolve::DEFAULT_LOCALE_RESOURCE, rustc_trait_selection::DEFAULT_LOCALE_RESOURCE, // tidy-alphabetical-end ]; @@ -1404,10 +1397,10 @@ fn parse_crate_attrs<'a>(sess: &'a Session) -> PResult<'a, ast::AttrVec> { /// Variant of `catch_fatal_errors` for the `interface::Result` return type /// that also computes the exit code. -pub fn catch_with_exit_code(f: impl FnOnce()) -> i32 { +pub fn catch_with_exit_code(f: impl FnOnce() -> T) -> ExitCode { match catch_fatal_errors(f) { - Ok(()) => EXIT_SUCCESS, - _ => EXIT_FAILURE, + Ok(status) => status.report(), + _ => ExitCode::FAILURE, } } @@ -1692,7 +1685,7 @@ pub fn install_ctrlc_handler() { .expect("Unable to install ctrlc handler"); } -pub fn main() -> ! { +pub fn main() -> ExitCode { let start_time = Instant::now(); let start_rss = get_resident_set_size(); @@ -1712,5 +1705,5 @@ pub fn main() -> ! { print_time_passes_entry("total", start_time.elapsed(), start_rss, end_rss, format); } - process::exit(exit_code) + exit_code } diff --git a/compiler/rustc_expand/Cargo.toml b/compiler/rustc_expand/Cargo.toml index a18506c42afcf..12b0c384a8aea 100644 --- a/compiler/rustc_expand/Cargo.toml +++ b/compiler/rustc_expand/Cargo.toml @@ -16,7 +16,6 @@ rustc_attr_parsing = { path = "../rustc_attr_parsing" } rustc_data_structures = { path = "../rustc_data_structures" } rustc_errors = { path = "../rustc_errors" } rustc_feature = { path = "../rustc_feature" } -rustc_fluent_macro = { path = "../rustc_fluent_macro" } rustc_hir = { path = "../rustc_hir" } rustc_lexer = { path = "../rustc_lexer" } rustc_lint_defs = { path = "../rustc_lint_defs" } diff --git a/compiler/rustc_expand/messages.ftl b/compiler/rustc_expand/messages.ftl deleted file mode 100644 index 851d78e0b1051..0000000000000 --- a/compiler/rustc_expand/messages.ftl +++ /dev/null @@ -1,207 +0,0 @@ -expand_attributes_on_expressions_experimental = - attributes on expressions are experimental - .help_outer_doc = `///` is used for outer documentation comments; for a plain comment, use `//` - .help_inner_doc = `//!` is used for inner documentation comments; for a plain comment, use `//` by removing the `!` or inserting a space in between them: `// !` - -expand_cfg_attr_no_attributes = `#[cfg_attr]` does not expand to any attributes - -expand_count_repetition_misplaced = - `count` can not be placed inside the innermost repetition - -expand_crate_name_in_cfg_attr = - `crate_name` within an `#![cfg_attr]` attribute is forbidden - -expand_crate_type_in_cfg_attr = - `crate_type` within an `#![cfg_attr]` attribute is forbidden - -expand_custom_attribute_panicked = - custom attribute panicked - .help = message: {$message} - -expand_duplicate_matcher_binding = duplicate matcher binding - .label = duplicate binding - .label2 = previous binding - -expand_empty_delegation_mac = - empty {$kind} delegation is not supported - -expand_expected_paren_or_brace = - expected `(` or `{"{"}`, found `{$token}` - -expand_explain_doc_comment_inner = - inner doc comments expand to `#![doc = "..."]`, which is what this macro attempted to match - -expand_explain_doc_comment_outer = - outer doc comments expand to `#[doc = "..."]`, which is what this macro attempted to match - -expand_expr_repeat_no_syntax_vars = - attempted to repeat an expression containing no syntax variables matched as repeating at this depth - -expand_feature_not_allowed = - the feature `{$name}` is not in the list of allowed features - -expand_feature_removed = - feature has been removed - .label = feature has been removed - .note = removed in {$removed_rustc_version}{$pull_note} - .reason = {$reason} - -expand_file_modules_in_proc_macro_input_are_unstable = - file modules in proc macro input are unstable - -expand_glob_delegation_outside_impls = - glob delegation is only supported in impls - -expand_glob_delegation_traitless_qpath = - qualified path without a trait in glob delegation - -expand_incomplete_parse = - macro expansion ignores {$descr} and any tokens following - .label = caused by the macro expansion here - .note = the usage of `{$macro_path}!` is likely invalid in {$kind_name} context - .suggestion_add_semi = you might be missing a semicolon here - -expand_invalid_cfg_expected_syntax = expected syntax is - -expand_invalid_cfg_multiple_predicates = multiple `cfg` predicates are specified -expand_invalid_cfg_no_parens = `cfg` is not followed by parentheses -expand_invalid_cfg_no_predicate = `cfg` predicate is not specified -expand_invalid_cfg_predicate_literal = `cfg` predicate key cannot be a literal - -expand_invalid_fragment_specifier = - invalid fragment specifier `{$fragment}` - .help = {$help} - -expand_macro_args_bad_delim = `{$rule_kw}` rule argument matchers require parentheses -expand_macro_args_bad_delim_sugg = the delimiters should be `(` and `)` - -expand_macro_body_stability = - macros cannot have body stability attributes - .label = invalid body stability attribute - .label2 = body stability attribute affects this macro - -expand_macro_call_unused_doc_comment = unused doc comment - .label = rustdoc does not generate documentation for macro invocations - .help = to document an item produced by a macro, the macro must produce the documentation as part of its expansion - -expand_macro_const_stability = - macros cannot have const stability attributes - .label = invalid const stability attribute - .label2 = const stability attribute affects this macro - -expand_macro_expands_to_match_arm = macros cannot expand to match arms - -expand_malformed_feature_attribute = - malformed `feature` attribute input - .expected = expected just one word - -expand_meta_var_dif_seq_matchers = {$msg} - -expand_metavar_still_repeating = variable `{$ident}` is still repeating at this depth - .label = expected repetition - -expand_metavariable_wrong_operator = meta-variable repeats with different Kleene operator - .binder_label = expected repetition - .occurrence_label = conflicting repetition - -expand_missing_fragment_specifier = missing fragment specifier - .note = fragment specifiers must be provided - .suggestion_add_fragspec = try adding a specifier here - .valid = {$valid} - -expand_module_circular = - circular modules: {$modules} - -expand_module_file_not_found = - file not found for module `{$name}` - .help = to create the module `{$name}`, create file "{$default_path}" or "{$secondary_path}" - .note = if there is a `mod {$name}` elsewhere in the crate already, import it with `use crate::...` instead - -expand_module_in_block = - cannot declare a file module inside a block unless it has a path attribute - .help = maybe `use` the module `{$name}` instead of redeclaring it - .note = file modules are usually placed outside of blocks, at the top level of the file - -expand_module_multiple_candidates = - file for module `{$name}` found at both "{$default_path}" and "{$secondary_path}" - .help = delete or rename one of them to remove the ambiguity - -expand_must_repeat_once = - this must repeat at least once - -expand_mve_extra_tokens = - unexpected trailing tokens - .label = for this metavariable expression - .range = the `{$name}` metavariable expression takes between {$min_or_exact_args} and {$max_args} arguments - .exact = the `{$name}` metavariable expression takes {$min_or_exact_args -> - [zero] no arguments - [one] a single argument - *[other] {$min_or_exact_args} arguments - } - .suggestion = try removing {$extra_count -> - [one] this token - *[other] these tokens - } - -expand_mve_missing_paren = - expected `(` - .label = for this this metavariable expression - .unexpected = unexpected token - .note = metavariable expressions use function-like parentheses syntax - .suggestion = try adding parentheses - -expand_mve_unrecognized_expr = - unrecognized metavariable expression - .label = not a valid metavariable expression - .note = valid metavariable expressions are {$valid_expr_list} - -expand_mve_unrecognized_var = - variable `{$key}` is not recognized in meta-variable expression - -expand_or_patterns_back_compat = the meaning of the `pat` fragment specifier is changing in Rust 2021, which may affect this macro - .suggestion = use pat_param to preserve semantics - -expand_proc_macro_back_compat = using an old version of `{$crate_name}` - .note = older versions of the `{$crate_name}` crate no longer compile; please update to `{$crate_name}` v{$fixed_version}, or switch to one of the `{$crate_name}` alternatives - -expand_proc_macro_derive_panicked = - proc-macro derive panicked - .help = message: {$message} - -expand_proc_macro_derive_tokens = - proc-macro derive produced unparsable tokens - -expand_proc_macro_panicked = - proc macro panicked - .help = message: {$message} - -expand_recursion_limit_reached = - recursion limit reached while expanding `{$descr}` - .help = consider increasing the recursion limit by adding a `#![recursion_limit = "{$suggested_limit}"]` attribute to your crate (`{$crate_name}`) - -expand_remove_expr_not_supported = - removing an expression is not supported in this position - -expand_remove_node_not_supported = - removing {$descr} is not supported in this position - -expand_resolve_relative_path = - cannot resolve relative path in non-file source `{$path}` - -expand_trace_macro = trace_macro - -expand_trailing_semi_macro = trailing semicolon in macro used in expression position - .note1 = macro invocations at the end of a block are treated as expressions - .note2 = to ignore the value produced by the macro, add a semicolon after the invocation of `{$name}` - -expand_unknown_macro_variable = unknown macro variable `{$name}` - -expand_unsupported_key_value = - key-value macro attributes are not supported - -expand_unused_builtin_attribute = unused attribute `{$attr_name}` - .note = the built-in attribute `{$attr_name}` will be ignored, since it's applied to the macro invocation `{$macro_name}` - .suggestion = remove the attribute - -expand_wrong_fragment_kind = - non-{$kind} macro in {$kind} position: {$name} diff --git a/compiler/rustc_expand/src/config.rs b/compiler/rustc_expand/src/config.rs index 1e1f98aef1b10..c9d0319a97c5d 100644 --- a/compiler/rustc_expand/src/config.rs +++ b/compiler/rustc_expand/src/config.rs @@ -15,6 +15,7 @@ use rustc_attr_parsing::{ AttributeParser, CFG_TEMPLATE, EvalConfigResult, ShouldEmit, eval_config_entry, parse_cfg, }; use rustc_data_structures::flat_map_in_place::FlatMapInPlace; +use rustc_errors::inline_fluent; use rustc_feature::{ ACCEPTED_LANG_FEATURES, EnabledLangFeature, EnabledLibFeature, Features, REMOVED_LANG_FEATURES, UNSTABLE_LANG_FEATURES, @@ -432,14 +433,14 @@ impl<'a> StripUnconfigured<'a> { &self.sess, sym::stmt_expr_attributes, attr.span, - crate::fluent_generated::expand_attributes_on_expressions_experimental, + inline_fluent!("attributes on expressions are experimental"), ); if attr.is_doc_comment() { err.help(if attr.style == AttrStyle::Outer { - crate::fluent_generated::expand_help_outer_doc + inline_fluent!("`///` is used for outer documentation comments; for a plain comment, use `//`") } else { - crate::fluent_generated::expand_help_inner_doc + inline_fluent!("`//!` is used for inner documentation comments; for a plain comment, use `//` by removing the `!` or inserting a space in between them: `// !`") }); } diff --git a/compiler/rustc_expand/src/errors.rs b/compiler/rustc_expand/src/errors.rs index 9f9764e060d1b..e64bfc136d16c 100644 --- a/compiler/rustc_expand/src/errors.rs +++ b/compiler/rustc_expand/src/errors.rs @@ -7,32 +7,34 @@ use rustc_macros::{Diagnostic, LintDiagnostic, Subdiagnostic}; use rustc_span::{Ident, MacroRulesNormalizedIdent, Span, Symbol}; #[derive(LintDiagnostic)] -#[diag(expand_cfg_attr_no_attributes)] +#[diag("`#[cfg_attr]` does not expand to any attributes")] pub(crate) struct CfgAttrNoAttributes; #[derive(Diagnostic)] -#[diag(expand_expr_repeat_no_syntax_vars)] +#[diag( + "attempted to repeat an expression containing no syntax variables matched as repeating at this depth" +)] pub(crate) struct NoSyntaxVarsExprRepeat { #[primary_span] pub span: Span, } #[derive(Diagnostic)] -#[diag(expand_must_repeat_once)] +#[diag("this must repeat at least once")] pub(crate) struct MustRepeatOnce { #[primary_span] pub span: Span, } #[derive(Diagnostic)] -#[diag(expand_count_repetition_misplaced)] +#[diag("`count` can not be placed inside the innermost repetition")] pub(crate) struct CountRepetitionMisplaced { #[primary_span] pub span: Span, } #[derive(Diagnostic)] -#[diag(expand_metavar_still_repeating)] +#[diag("variable `{$ident}` is still repeating at this depth")] pub(crate) struct MacroVarStillRepeating { #[primary_span] pub span: Span, @@ -40,24 +42,24 @@ pub(crate) struct MacroVarStillRepeating { } #[derive(LintDiagnostic)] -#[diag(expand_metavar_still_repeating)] +#[diag("variable `{$ident}` is still repeating at this depth")] pub(crate) struct MetaVarStillRepeatingLint { - #[label] + #[label("expected repetition")] pub label: Span, pub ident: MacroRulesNormalizedIdent, } #[derive(LintDiagnostic)] -#[diag(expand_metavariable_wrong_operator)] +#[diag("meta-variable repeats with different Kleene operator")] pub(crate) struct MetaVariableWrongOperator { - #[label(expand_binder_label)] + #[label("expected repetition")] pub binder: Span, - #[label(expand_occurrence_label)] + #[label("conflicting repetition")] pub occurrence: Span, } #[derive(Diagnostic)] -#[diag(expand_meta_var_dif_seq_matchers)] +#[diag("{$msg}")] pub(crate) struct MetaVarsDifSeqMatchers { #[primary_span] pub span: Span, @@ -65,13 +67,13 @@ pub(crate) struct MetaVarsDifSeqMatchers { } #[derive(LintDiagnostic)] -#[diag(expand_unknown_macro_variable)] +#[diag("unknown macro variable `{$name}`")] pub(crate) struct UnknownMacroVariable { pub name: MacroRulesNormalizedIdent, } #[derive(Diagnostic)] -#[diag(expand_resolve_relative_path)] +#[diag("cannot resolve relative path in non-file source `{$path}`")] pub(crate) struct ResolveRelativePath { #[primary_span] pub span: Span, @@ -79,31 +81,31 @@ pub(crate) struct ResolveRelativePath { } #[derive(Diagnostic)] -#[diag(expand_macro_const_stability)] +#[diag("macros cannot have const stability attributes")] pub(crate) struct MacroConstStability { #[primary_span] - #[label] + #[label("invalid const stability attribute")] pub span: Span, - #[label(expand_label2)] + #[label("const stability attribute affects this macro")] pub head_span: Span, } #[derive(Diagnostic)] -#[diag(expand_macro_body_stability)] +#[diag("macros cannot have body stability attributes")] pub(crate) struct MacroBodyStability { #[primary_span] - #[label] + #[label("invalid body stability attribute")] pub span: Span, - #[label(expand_label2)] + #[label("body stability attribute affects this macro")] pub head_span: Span, } #[derive(Diagnostic)] -#[diag(expand_feature_removed, code = E0557)] -#[note] +#[diag("feature has been removed", code = E0557)] +#[note("removed in {$removed_rustc_version}{$pull_note}")] pub(crate) struct FeatureRemoved<'a> { #[primary_span] - #[label] + #[label("feature has been removed")] pub span: Span, #[subdiagnostic] pub reason: Option>, @@ -112,13 +114,13 @@ pub(crate) struct FeatureRemoved<'a> { } #[derive(Subdiagnostic)] -#[note(expand_reason)] +#[note("{$reason}")] pub(crate) struct FeatureRemovedReason<'a> { pub reason: &'a str, } #[derive(Diagnostic)] -#[diag(expand_feature_not_allowed, code = E0725)] +#[diag("the feature `{$name}` is not in the list of allowed features", code = E0725)] pub(crate) struct FeatureNotAllowed { #[primary_span] pub span: Span, @@ -126,8 +128,10 @@ pub(crate) struct FeatureNotAllowed { } #[derive(Diagnostic)] -#[diag(expand_recursion_limit_reached)] -#[help] +#[diag("recursion limit reached while expanding `{$descr}`")] +#[help( + "consider increasing the recursion limit by adding a `#![recursion_limit = \"{$suggested_limit}\"]` attribute to your crate (`{$crate_name}`)" +)] pub(crate) struct RecursionLimitReached { #[primary_span] pub span: Span, @@ -137,7 +141,7 @@ pub(crate) struct RecursionLimitReached { } #[derive(Diagnostic)] -#[diag(expand_malformed_feature_attribute, code = E0556)] +#[diag("malformed `feature` attribute input", code = E0556)] pub(crate) struct MalformedFeatureAttribute { #[primary_span] pub span: Span, @@ -147,12 +151,16 @@ pub(crate) struct MalformedFeatureAttribute { #[derive(Subdiagnostic)] pub(crate) enum MalformedFeatureAttributeHelp { - #[label(expand_expected)] + #[label("expected just one word")] Label { #[primary_span] span: Span, }, - #[suggestion(expand_expected, code = "{suggestion}", applicability = "maybe-incorrect")] + #[suggestion( + "expected just one word", + code = "{suggestion}", + applicability = "maybe-incorrect" + )] Suggestion { #[primary_span] span: Span, @@ -161,7 +169,7 @@ pub(crate) enum MalformedFeatureAttributeHelp { } #[derive(Diagnostic)] -#[diag(expand_remove_expr_not_supported)] +#[diag("removing an expression is not supported in this position")] pub(crate) struct RemoveExprNotSupported { #[primary_span] pub span: Span, @@ -169,32 +177,32 @@ pub(crate) struct RemoveExprNotSupported { #[derive(Diagnostic)] pub(crate) enum InvalidCfg { - #[diag(expand_invalid_cfg_no_parens)] + #[diag("`cfg` is not followed by parentheses")] NotFollowedByParens { #[primary_span] #[suggestion( - expand_invalid_cfg_expected_syntax, + "expected syntax is", code = "cfg(/* predicate */)", applicability = "has-placeholders" )] span: Span, }, - #[diag(expand_invalid_cfg_no_predicate)] + #[diag("`cfg` predicate is not specified")] NoPredicate { #[primary_span] #[suggestion( - expand_invalid_cfg_expected_syntax, + "expected syntax is", code = "cfg(/* predicate */)", applicability = "has-placeholders" )] span: Span, }, - #[diag(expand_invalid_cfg_multiple_predicates)] + #[diag("multiple `cfg` predicates are specified")] MultiplePredicates { #[primary_span] span: Span, }, - #[diag(expand_invalid_cfg_predicate_literal)] + #[diag("`cfg` predicate key cannot be a literal")] PredicateLiteral { #[primary_span] span: Span, @@ -202,7 +210,7 @@ pub(crate) enum InvalidCfg { } #[derive(Diagnostic)] -#[diag(expand_wrong_fragment_kind)] +#[diag("non-{$kind} macro in {$kind} position: {$name}")] pub(crate) struct WrongFragmentKind<'a> { #[primary_span] pub span: Span, @@ -211,28 +219,28 @@ pub(crate) struct WrongFragmentKind<'a> { } #[derive(Diagnostic)] -#[diag(expand_unsupported_key_value)] +#[diag("key-value macro attributes are not supported")] pub(crate) struct UnsupportedKeyValue { #[primary_span] pub span: Span, } #[derive(Diagnostic)] -#[diag(expand_incomplete_parse)] -#[note] +#[diag("macro expansion ignores {$descr} and any tokens following")] +#[note("the usage of `{$macro_path}!` is likely invalid in {$kind_name} context")] pub(crate) struct IncompleteParse<'a> { #[primary_span] pub span: Span, pub descr: String, - #[label] + #[label("caused by the macro expansion here")] pub label_span: Span, pub macro_path: &'a ast::Path, pub kind_name: &'a str, - #[note(expand_macro_expands_to_match_arm)] + #[note("macros cannot expand to match arms")] pub expands_to_match_arm: bool, #[suggestion( - expand_suggestion_add_semi, + "you might be missing a semicolon here", style = "verbose", code = ";", applicability = "maybe-incorrect" @@ -241,7 +249,7 @@ pub(crate) struct IncompleteParse<'a> { } #[derive(Diagnostic)] -#[diag(expand_remove_node_not_supported)] +#[diag("removing {$descr} is not supported in this position")] pub(crate) struct RemoveNodeNotSupported { #[primary_span] pub span: Span, @@ -249,7 +257,7 @@ pub(crate) struct RemoveNodeNotSupported { } #[derive(Diagnostic)] -#[diag(expand_module_circular)] +#[diag("circular modules: {$modules}")] pub(crate) struct ModuleCircular { #[primary_span] pub span: Span, @@ -257,8 +265,8 @@ pub(crate) struct ModuleCircular { } #[derive(Diagnostic)] -#[diag(expand_module_in_block)] -#[note] +#[diag("cannot declare a file module inside a block unless it has a path attribute")] +#[note("file modules are usually placed outside of blocks, at the top level of the file")] pub(crate) struct ModuleInBlock { #[primary_span] pub span: Span, @@ -267,7 +275,7 @@ pub(crate) struct ModuleInBlock { } #[derive(Subdiagnostic)] -#[help(expand_help)] +#[help("maybe `use` the module `{$name}` instead of redeclaring it")] pub(crate) struct ModuleInBlockName { #[primary_span] pub span: Span, @@ -275,9 +283,11 @@ pub(crate) struct ModuleInBlockName { } #[derive(Diagnostic)] -#[diag(expand_module_file_not_found, code = E0583)] -#[help] -#[note] +#[diag("file not found for module `{$name}`", code = E0583)] +#[help("to create the module `{$name}`, create file \"{$default_path}\" or \"{$secondary_path}\"")] +#[note( + "if there is a `mod {$name}` elsewhere in the crate already, import it with `use crate::...` instead" +)] pub(crate) struct ModuleFileNotFound { #[primary_span] pub span: Span, @@ -287,8 +297,8 @@ pub(crate) struct ModuleFileNotFound { } #[derive(Diagnostic)] -#[diag(expand_module_multiple_candidates, code = E0761)] -#[help] +#[diag("file for module `{$name}` found at both \"{$default_path}\" and \"{$secondary_path}\"", code = E0761)] +#[help("delete or rename one of them to remove the ambiguity")] pub(crate) struct ModuleMultipleCandidates { #[primary_span] pub span: Span, @@ -298,14 +308,14 @@ pub(crate) struct ModuleMultipleCandidates { } #[derive(Diagnostic)] -#[diag(expand_trace_macro)] +#[diag("trace_macro")] pub(crate) struct TraceMacro { #[primary_span] pub span: Span, } #[derive(Diagnostic)] -#[diag(expand_proc_macro_panicked)] +#[diag("proc macro panicked")] pub(crate) struct ProcMacroPanicked { #[primary_span] pub span: Span, @@ -314,13 +324,13 @@ pub(crate) struct ProcMacroPanicked { } #[derive(Subdiagnostic)] -#[help(expand_help)] +#[help("message: {$message}")] pub(crate) struct ProcMacroPanickedHelp { pub message: String, } #[derive(Diagnostic)] -#[diag(expand_proc_macro_derive_panicked)] +#[diag("proc-macro derive panicked")] pub(crate) struct ProcMacroDerivePanicked { #[primary_span] pub span: Span, @@ -329,13 +339,13 @@ pub(crate) struct ProcMacroDerivePanicked { } #[derive(Subdiagnostic)] -#[help(expand_help)] +#[help("message: {$message}")] pub(crate) struct ProcMacroDerivePanickedHelp { pub message: String, } #[derive(Diagnostic)] -#[diag(expand_custom_attribute_panicked)] +#[diag("custom attribute panicked")] pub(crate) struct CustomAttributePanicked { #[primary_span] pub span: Span, @@ -344,46 +354,46 @@ pub(crate) struct CustomAttributePanicked { } #[derive(Subdiagnostic)] -#[help(expand_help)] +#[help("message: {$message}")] pub(crate) struct CustomAttributePanickedHelp { pub message: String, } #[derive(Diagnostic)] -#[diag(expand_proc_macro_derive_tokens)] +#[diag("proc-macro derive produced unparsable tokens")] pub(crate) struct ProcMacroDeriveTokens { #[primary_span] pub span: Span, } #[derive(Diagnostic)] -#[diag(expand_duplicate_matcher_binding)] +#[diag("duplicate matcher binding")] pub(crate) struct DuplicateMatcherBinding { #[primary_span] - #[label] + #[label("duplicate binding")] pub span: Span, - #[label(expand_label2)] + #[label("previous binding")] pub prev: Span, } #[derive(LintDiagnostic)] -#[diag(expand_duplicate_matcher_binding)] +#[diag("duplicate matcher binding")] pub(crate) struct DuplicateMatcherBindingLint { - #[label] + #[label("duplicate binding")] pub span: Span, - #[label(expand_label2)] + #[label("previous binding")] pub prev: Span, } #[derive(Diagnostic)] -#[diag(expand_missing_fragment_specifier)] -#[note] -#[help(expand_valid)] +#[diag("missing fragment specifier")] +#[note("fragment specifiers must be provided")] +#[help("{$valid}")] pub(crate) struct MissingFragmentSpecifier { #[primary_span] pub span: Span, #[suggestion( - expand_suggestion_add_fragspec, + "try adding a specifier here", style = "verbose", code = ":spec", applicability = "maybe-incorrect" @@ -393,8 +403,8 @@ pub(crate) struct MissingFragmentSpecifier { } #[derive(Diagnostic)] -#[diag(expand_invalid_fragment_specifier)] -#[help] +#[diag("invalid fragment specifier `{$fragment}`")] +#[help("{$help}")] pub(crate) struct InvalidFragmentSpecifier { #[primary_span] pub span: Span, @@ -403,7 +413,7 @@ pub(crate) struct InvalidFragmentSpecifier { } #[derive(Diagnostic)] -#[diag(expand_expected_paren_or_brace)] +#[diag("expected `(` or `{\"{\"}`, found `{$token}`")] pub(crate) struct ExpectedParenOrBrace<'a> { #[primary_span] pub span: Span, @@ -411,7 +421,7 @@ pub(crate) struct ExpectedParenOrBrace<'a> { } #[derive(Diagnostic)] -#[diag(expand_empty_delegation_mac)] +#[diag("empty {$kind} delegation is not supported")] pub(crate) struct EmptyDelegationMac { #[primary_span] pub span: Span, @@ -419,28 +429,28 @@ pub(crate) struct EmptyDelegationMac { } #[derive(Diagnostic)] -#[diag(expand_glob_delegation_outside_impls)] +#[diag("glob delegation is only supported in impls")] pub(crate) struct GlobDelegationOutsideImpls { #[primary_span] pub span: Span, } #[derive(Diagnostic)] -#[diag(expand_crate_name_in_cfg_attr)] +#[diag("`crate_name` within an `#![cfg_attr]` attribute is forbidden")] pub(crate) struct CrateNameInCfgAttr { #[primary_span] pub span: Span, } #[derive(Diagnostic)] -#[diag(expand_crate_type_in_cfg_attr)] +#[diag("`crate_type` within an `#![cfg_attr]` attribute is forbidden")] pub(crate) struct CrateTypeInCfgAttr { #[primary_span] pub span: Span, } #[derive(Diagnostic)] -#[diag(expand_glob_delegation_traitless_qpath)] +#[diag("qualified path without a trait in glob delegation")] pub(crate) struct GlobDelegationTraitlessQpath { #[primary_span] pub span: Span, @@ -449,8 +459,10 @@ pub(crate) struct GlobDelegationTraitlessQpath { // This used to be the `proc_macro_back_compat` lint (#83125). It was later // turned into a hard error. #[derive(Diagnostic)] -#[diag(expand_proc_macro_back_compat)] -#[note] +#[diag("using an old version of `{$crate_name}`")] +#[note( + "older versions of the `{$crate_name}` crate no longer compile; please update to `{$crate_name}` v{$fixed_version}, or switch to one of the `{$crate_name}` alternatives" +)] pub(crate) struct ProcMacroBackCompat { pub crate_name: String, pub fixed_version: String, @@ -461,20 +473,35 @@ mod metavar_exprs { use super::*; #[derive(Diagnostic, Default)] - #[diag(expand_mve_extra_tokens)] + #[diag("unexpected trailing tokens")] pub(crate) struct MveExtraTokens { #[primary_span] - #[suggestion(code = "", applicability = "machine-applicable")] + #[suggestion( + "try removing {$extra_count -> + [one] this token + *[other] these tokens + }", + code = "", + applicability = "machine-applicable" + )] pub span: Span, - #[label] + #[label("for this metavariable expression")] pub ident_span: Span, pub extra_count: usize, // The rest is only used for specific diagnostics and can be default if neither // `note` is `Some`. - #[note(expand_exact)] + #[note( + "the `{$name}` metavariable expression takes {$min_or_exact_args -> + [zero] no arguments + [one] a single argument + *[other] {$min_or_exact_args} arguments + }" + )] pub exact_args_note: Option<()>, - #[note(expand_range)] + #[note( + "the `{$name}` metavariable expression takes between {$min_or_exact_args} and {$max_args} arguments" + )] pub range_args_note: Option<()>, pub min_or_exact_args: usize, pub max_args: usize, @@ -482,30 +509,34 @@ mod metavar_exprs { } #[derive(Diagnostic)] - #[note] - #[diag(expand_mve_missing_paren)] + #[note("metavariable expressions use function-like parentheses syntax")] + #[diag("expected `(`")] pub(crate) struct MveMissingParen { #[primary_span] - #[label] + #[label("for this this metavariable expression")] pub ident_span: Span, - #[label(expand_unexpected)] + #[label("unexpected token")] pub unexpected_span: Option, - #[suggestion(code = "( /* ... */ )", applicability = "has-placeholders")] + #[suggestion( + "try adding parentheses", + code = "( /* ... */ )", + applicability = "has-placeholders" + )] pub insert_span: Option, } #[derive(Diagnostic)] - #[note] - #[diag(expand_mve_unrecognized_expr)] + #[note("valid metavariable expressions are {$valid_expr_list}")] + #[diag("unrecognized metavariable expression")] pub(crate) struct MveUnrecognizedExpr { #[primary_span] - #[label] + #[label("not a valid metavariable expression")] pub span: Span, pub valid_expr_list: &'static str, } #[derive(Diagnostic)] - #[diag(expand_mve_unrecognized_var)] + #[diag("variable `{$key}` is not recognized in meta-variable expression")] pub(crate) struct MveUnrecognizedVar { #[primary_span] pub span: Span, @@ -514,7 +545,7 @@ mod metavar_exprs { } #[derive(Diagnostic)] -#[diag(expand_macro_args_bad_delim)] +#[diag("`{$rule_kw}` rule argument matchers require parentheses")] pub(crate) struct MacroArgsBadDelim { #[primary_span] pub span: Span, @@ -524,7 +555,10 @@ pub(crate) struct MacroArgsBadDelim { } #[derive(Subdiagnostic)] -#[multipart_suggestion(expand_macro_args_bad_delim_sugg, applicability = "machine-applicable")] +#[multipart_suggestion( + "the delimiters should be `(` and `)`", + applicability = "machine-applicable" +)] pub(crate) struct MacroArgsBadDelimSugg { #[suggestion_part(code = "(")] pub open: Span, @@ -533,37 +567,54 @@ pub(crate) struct MacroArgsBadDelimSugg { } #[derive(LintDiagnostic)] -#[diag(expand_macro_call_unused_doc_comment)] -#[help] +#[diag("unused doc comment")] +#[help( + "to document an item produced by a macro, the macro must produce the documentation as part of its expansion" +)] pub(crate) struct MacroCallUnusedDocComment { - #[label] + #[label("rustdoc does not generate documentation for macro invocations")] pub span: Span, } #[derive(LintDiagnostic)] -#[diag(expand_or_patterns_back_compat)] +#[diag( + "the meaning of the `pat` fragment specifier is changing in Rust 2021, which may affect this macro" +)] pub(crate) struct OrPatternsBackCompat { - #[suggestion(code = "{suggestion}", applicability = "machine-applicable")] + #[suggestion( + "use pat_param to preserve semantics", + code = "{suggestion}", + applicability = "machine-applicable" + )] pub span: Span, pub suggestion: String, } #[derive(LintDiagnostic)] -#[diag(expand_trailing_semi_macro)] +#[diag("trailing semicolon in macro used in expression position")] pub(crate) struct TrailingMacro { - #[note(expand_note1)] - #[note(expand_note2)] + #[note("macro invocations at the end of a block are treated as expressions")] + #[note( + "to ignore the value produced by the macro, add a semicolon after the invocation of `{$name}`" + )] pub is_trailing: bool, pub name: Ident, } #[derive(LintDiagnostic)] -#[diag(expand_unused_builtin_attribute)] +#[diag("unused attribute `{$attr_name}`")] pub(crate) struct UnusedBuiltinAttribute { - #[note] + #[note( + "the built-in attribute `{$attr_name}` will be ignored, since it's applied to the macro invocation `{$macro_name}`" + )] pub invoc_span: Span, pub attr_name: Symbol, pub macro_name: String, - #[suggestion(code = "", applicability = "machine-applicable", style = "tool-only")] + #[suggestion( + "remove the attribute", + code = "", + applicability = "machine-applicable", + style = "tool-only" + )] pub attr_span: Span, } diff --git a/compiler/rustc_expand/src/expand.rs b/compiler/rustc_expand/src/expand.rs index 449dc95ea3720..da678ff703464 100644 --- a/compiler/rustc_expand/src/expand.rs +++ b/compiler/rustc_expand/src/expand.rs @@ -19,7 +19,7 @@ use rustc_attr_parsing::{ }; use rustc_data_structures::flat_map_in_place::FlatMapInPlace; use rustc_data_structures::stack::ensure_sufficient_stack; -use rustc_errors::PResult; +use rustc_errors::{PResult, inline_fluent}; use rustc_feature::Features; use rustc_hir::Target; use rustc_hir::def::MacroKinds; @@ -42,7 +42,6 @@ use crate::errors::{ RecursionLimitReached, RemoveExprNotSupported, RemoveNodeNotSupported, UnsupportedKeyValue, WrongFragmentKind, }; -use crate::fluent_generated; use crate::mbe::diagnostics::annotate_err_with_kind; use crate::module::{ DirOwnership, ParsedExternalMod, mod_dir_path, mod_file_path_from_attr, parse_external_mod, @@ -1052,7 +1051,7 @@ impl<'a, 'b> MacroExpander<'a, 'b> { self.sess, sym::proc_macro_hygiene, item.span, - fluent_generated::expand_file_modules_in_proc_macro_input_are_unstable, + inline_fluent!("file modules in proc macro input are unstable"), ) .emit(); } diff --git a/compiler/rustc_expand/src/lib.rs b/compiler/rustc_expand/src/lib.rs index 89540a9a5c5b4..96f17418b8d2d 100644 --- a/compiler/rustc_expand/src/lib.rs +++ b/compiler/rustc_expand/src/lib.rs @@ -26,5 +26,3 @@ pub mod proc_macro; pub fn provide(providers: &mut rustc_middle::query::Providers) { providers.derive_macro_expansion = proc_macro::provide_derive_macro_expansion; } - -rustc_fluent_macro::fluent_messages! { "../messages.ftl" } diff --git a/compiler/rustc_expand/src/mbe/diagnostics.rs b/compiler/rustc_expand/src/mbe/diagnostics.rs index f5edaf50edd52..df6903dc4937f 100644 --- a/compiler/rustc_expand/src/mbe/diagnostics.rs +++ b/compiler/rustc_expand/src/mbe/diagnostics.rs @@ -302,12 +302,16 @@ pub(crate) fn annotate_err_with_kind(err: &mut Diag<'_>, kind: AstFragmentKind, #[derive(Subdiagnostic)] enum ExplainDocComment { - #[label(expand_explain_doc_comment_inner)] + #[label( + "inner doc comments expand to `#![doc = \"...\"]`, which is what this macro attempted to match" + )] Inner { #[primary_span] span: Span, }, - #[label(expand_explain_doc_comment_outer)] + #[label( + "outer doc comments expand to `#[doc = \"...\"]`, which is what this macro attempted to match" + )] Outer { #[primary_span] span: Span, diff --git a/compiler/rustc_feature/src/unstable.rs b/compiler/rustc_feature/src/unstable.rs index c99af9658cdef..e2abf50cbd397 100644 --- a/compiler/rustc_feature/src/unstable.rs +++ b/compiler/rustc_feature/src/unstable.rs @@ -373,6 +373,8 @@ declare_features! ( (unstable, async_for_loop, "1.77.0", Some(118898)), /// Allows `async` trait bound modifier. (unstable, async_trait_bounds, "1.85.0", Some(62290)), + /// Target features on avr. + (unstable, avr_target_feature, "CURRENT_RUSTC_VERSION", Some(146889)), /// Allows using Intel AVX10 target features and intrinsics (unstable, avx10_target_feature, "1.88.0", Some(138843)), /// Target features on bpf. diff --git a/compiler/rustc_hir/src/attrs/data_structures.rs b/compiler/rustc_hir/src/attrs/data_structures.rs index a53eff4637ff2..a444b5e4badf5 100644 --- a/compiler/rustc_hir/src/attrs/data_structures.rs +++ b/compiler/rustc_hir/src/attrs/data_structures.rs @@ -716,6 +716,23 @@ pub enum BorrowckGraphvizFormatKind { TwoPhase, } +#[derive(Clone, Debug, PartialEq, Eq)] +#[derive(HashStable_Generic, Encodable, Decodable, PrintAttribute)] +pub struct RustcCleanAttribute { + pub span: Span, + pub cfg: Symbol, + pub except: Option, + pub loaded_from_disk: Option, +} + +/// Represents the `except=` or `loaded_from_disk=` argument of `#[rustc_clean]` +#[derive(Clone, Debug, PartialEq, Eq)] +#[derive(HashStable_Generic, Encodable, Decodable, PrintAttribute)] +pub struct RustcCleanQueries { + pub entries: ThinVec, + pub span: Span, +} + /// Represents parsed *built-in* inert attributes. /// /// ## Overview @@ -992,6 +1009,9 @@ pub enum AttributeKind { /// Represents [`#[recursion_limit]`](https://doc.rust-lang.org/reference/attributes/limits.html#the-recursion_limit-attribute) RecursionLimit { attr_span: Span, limit_span: Span, limit: Limit }, + /// Represents `#[reexport_test_harness_main]` + ReexportTestHarnessMain(Symbol), + /// Represents [`#[repr]`](https://doc.rust-lang.org/stable/reference/type-layout.html#representations). Repr { reprs: ThinVec<(ReprAttr, Span)>, first_span: Span }, @@ -1022,6 +1042,9 @@ pub enum AttributeKind { /// Represents `#[rustc_builtin_macro]`. RustcBuiltinMacro { builtin_name: Option, helper_attrs: ThinVec, span: Span }, + /// Represents `#[rustc_clean]` + RustcClean(ThinVec), + /// Represents `#[rustc_coherence_is_core]` RustcCoherenceIsCore(Span), @@ -1077,6 +1100,9 @@ pub enum AttributeKind { /// Represents `#[rustc_hidden_type_of_opaques]` RustcHiddenTypeOfOpaques, + /// Represents `#[rustc_if_this_changed]` + RustcIfThisChanged(Span, Option), + /// Represents `#[rustc_layout]` RustcLayout(ThinVec), @@ -1178,6 +1204,9 @@ pub enum AttributeKind { /// Represents `#[rustc_std_internal_symbol]`. RustcStdInternalSymbol(Span), + /// Represents `#[rustc_then_this_would_need]` + RustcThenThisWouldNeed(Span, ThinVec), + /// Represents `#[rustc_unsafe_specialization_marker]`. RustcUnsafeSpecializationMarker(Span), diff --git a/compiler/rustc_hir/src/attrs/encode_cross_crate.rs b/compiler/rustc_hir/src/attrs/encode_cross_crate.rs index 7ec1920152a5e..b6249e1e2ec2c 100644 --- a/compiler/rustc_hir/src/attrs/encode_cross_crate.rs +++ b/compiler/rustc_hir/src/attrs/encode_cross_crate.rs @@ -87,6 +87,7 @@ impl AttributeKind { ProcMacroDerive { .. } => No, ProfilerRuntime => No, RecursionLimit { .. } => No, + ReexportTestHarnessMain(..) => No, Repr { .. } => No, RustcAllocator => No, RustcAllocatorZeroed => No, @@ -96,6 +97,7 @@ impl AttributeKind { RustcAsPtr(..) => Yes, RustcBodyStability { .. } => No, RustcBuiltinMacro { .. } => Yes, + RustcClean { .. } => No, RustcCoherenceIsCore(..) => No, RustcCoinductive(..) => No, RustcConfusables { .. } => Yes, @@ -112,6 +114,7 @@ impl AttributeKind { RustcDynIncompatibleTrait(..) => No, RustcHasIncoherentInherentImpls => Yes, RustcHiddenTypeOfOpaques => No, + RustcIfThisChanged(..) => No, RustcLayout(..) => No, RustcLayoutScalarValidRangeEnd(..) => Yes, RustcLayoutScalarValidRangeStart(..) => Yes, @@ -144,6 +147,7 @@ impl AttributeKind { RustcSkipDuringMethodDispatch { .. } => No, RustcSpecializationTrait(..) => No, RustcStdInternalSymbol(..) => No, + RustcThenThisWouldNeed(..) => No, RustcUnsafeSpecializationMarker(..) => No, RustcVariance => No, RustcVarianceOfOpaques => No, diff --git a/compiler/rustc_hir/src/attrs/pretty_printing.rs b/compiler/rustc_hir/src/attrs/pretty_printing.rs index bd268d2c423f7..20efd72e20f7f 100644 --- a/compiler/rustc_hir/src/attrs/pretty_printing.rs +++ b/compiler/rustc_hir/src/attrs/pretty_printing.rs @@ -6,7 +6,7 @@ use rustc_abi::Align; use rustc_ast::attr::data_structures::CfgEntry; use rustc_ast::attr::version::RustcVersion; use rustc_ast::token::{CommentKind, DocFragmentKind}; -use rustc_ast::{AttrStyle, IntTy, UintTy}; +use rustc_ast::{AttrId, AttrStyle, IntTy, UintTy}; use rustc_ast_pretty::pp::Printer; use rustc_data_structures::fx::FxIndexMap; use rustc_span::def_id::DefId; @@ -179,7 +179,7 @@ macro_rules! print_tup { } print_tup!(A B C D E F G H); -print_skip!(Span, (), ErrorGuaranteed); +print_skip!(Span, (), ErrorGuaranteed, AttrId); print_disp!(u8, u16, u128, usize, bool, NonZero, Limit); print_debug!( Symbol, diff --git a/compiler/rustc_hir_typeck/Cargo.toml b/compiler/rustc_hir_typeck/Cargo.toml index 246134665174a..43db09b0eab8f 100644 --- a/compiler/rustc_hir_typeck/Cargo.toml +++ b/compiler/rustc_hir_typeck/Cargo.toml @@ -10,7 +10,6 @@ rustc_abi = { path = "../rustc_abi" } rustc_ast = { path = "../rustc_ast" } rustc_data_structures = { path = "../rustc_data_structures" } rustc_errors = { path = "../rustc_errors" } -rustc_fluent_macro = { path = "../rustc_fluent_macro" } rustc_hir = { path = "../rustc_hir" } rustc_hir_analysis = { path = "../rustc_hir_analysis" } rustc_hir_pretty = { path = "../rustc_hir_pretty" } diff --git a/compiler/rustc_hir_typeck/messages.ftl b/compiler/rustc_hir_typeck/messages.ftl deleted file mode 100644 index 0c4b1f891eadb..0000000000000 --- a/compiler/rustc_hir_typeck/messages.ftl +++ /dev/null @@ -1,315 +0,0 @@ -hir_typeck_abi_cannot_be_called = - functions with the {$abi} ABI cannot be called - .note = an `extern {$abi}` function can only be called using inline assembly - -hir_typeck_add_missing_parentheses_in_range = you must surround the range in parentheses to call its `{$func_name}` function - -hir_typeck_add_return_type_add = try adding a return type - -hir_typeck_add_return_type_missing_here = a return type might be missing here - -hir_typeck_address_of_temporary_taken = cannot take address of a temporary - .label = temporary value - -hir_typeck_arg_mismatch_indeterminate = argument type mismatch was detected, but rustc had trouble determining where - .note = we would appreciate a bug report: https://github.com/rust-lang/rust/issues/new - -hir_typeck_as_deref_suggestion = consider using `as_deref` here -hir_typeck_base_expression_double_dot = base expression required after `..` -hir_typeck_base_expression_double_dot_add_expr = add a base expression here -hir_typeck_base_expression_double_dot_enable_default_field_values = - add `#![feature(default_field_values)]` to the crate attributes to enable default values on `struct` fields -hir_typeck_base_expression_double_dot_remove = remove the `..` as all the fields are already present - -hir_typeck_break_inside_closure = - `{$name}` inside of a closure - .label = cannot `{$name}` inside of a closure - .closure_label = enclosing closure - -hir_typeck_break_inside_coroutine = - `{$name}` inside `{$kind}` {$source} - .label = cannot `{$name}` inside `{$kind}` {$source} - .coroutine_label = enclosing `{$kind}` {$source} - -hir_typeck_break_non_loop = - `break` with value from a `{$kind}` loop - .label = can only break with a value inside `loop` or breakable block - .label2 = you can't `break` with a value in a `{$kind}` loop - .suggestion = use `break` on its own without a value inside this `{$kind}` loop - .break_expr_suggestion = alternatively, you might have meant to use the available loop label - - -hir_typeck_candidate_trait_note = `{$trait_name}` defines an item `{$item_name}`{$action_or_ty -> - [NONE] {""} - [implement] , perhaps you need to implement it - *[other] , perhaps you need to restrict type parameter `{$action_or_ty}` with it -} - -hir_typeck_cannot_cast_to_bool = cannot cast `{$expr_ty}` as `bool` - .suggestion = compare with zero instead - .help = compare with zero instead - .label = unsupported cast - -hir_typeck_cant_dereference = type `{$ty}` cannot be dereferenced -hir_typeck_cant_dereference_label = can't be dereferenced - -hir_typeck_cast_enum_drop = cannot cast enum `{$expr_ty}` into integer `{$cast_ty}` because it implements `Drop` - -hir_typeck_cast_thin_pointer_to_wide_pointer = cannot cast thin pointer `{$expr_ty}` to wide pointer `{$cast_ty}` - .teach_help = Thin pointers are "simple" pointers: they are purely a reference to a - memory address. - - Wide pointers are pointers referencing "Dynamically Sized Types" (also - called DST). DST don't have a statically known size, therefore they can - only exist behind some kind of pointers that contain additional - information. Slices and trait objects are DSTs. In the case of slices, - the additional information the wide pointer holds is their size. - - To fix this error, don't try to cast directly between thin and wide - pointers. - - For more information about casts, take a look at The Book: - https://doc.rust-lang.org/reference/expressions/operator-expr.html#type-cast-expressions", - -hir_typeck_cast_unknown_pointer = cannot cast {$to -> - [true] to - *[false] from - } a pointer of an unknown kind - .label_to = needs more type information - .note = the type information given here is insufficient to check whether the pointer cast is valid - .label_from = the type information given here is insufficient to check whether the pointer cast is valid - -hir_typeck_const_continue_bad_label = - `#[const_continue]` must break to a labeled block that participates in a `#[loop_match]` - -hir_typeck_continue_labeled_block = - `continue` pointing to a labeled block - .label = labeled blocks cannot be `continue`'d - .block_label = labeled block the `continue` points to - - -hir_typeck_convert_to_str = try converting the passed type into a `&str` - -hir_typeck_convert_using_method = try using `{$sugg}` to convert `{$found}` to `{$expected}` - -hir_typeck_ctor_is_private = tuple struct constructor `{$def}` is private - -hir_typeck_dependency_on_unit_never_type_fallback = this function depends on never type fallback being `()` - .note = in edition 2024, the requirement `{$obligation}` will fail - .help = specify the types explicitly - -hir_typeck_deref_is_empty = this expression `Deref`s to `{$deref_ty}` which implements `is_empty` - -hir_typeck_expected_array_or_slice = expected an array or slice, found `{$ty}` -hir_typeck_expected_array_or_slice_label = pattern cannot match with input type `{$ty}` - -hir_typeck_expected_default_return_type = expected `()` because of default return type - -hir_typeck_expected_return_type = expected `{$expected}` because of return type - -hir_typeck_explicit_destructor = explicit use of destructor method - .label = explicit destructor calls not allowed - .suggestion = consider using `drop` function - -hir_typeck_field_multiply_specified_in_initializer = - field `{$ident}` specified more than once - .label = used more than once - .previous_use_label = first use of `{$ident}` - -hir_typeck_fn_item_to_variadic_function = can't pass a function item to a variadic function - .suggestion = use a function pointer instead - .help = a function item is zero-sized and needs to be cast into a function pointer to be used in FFI - .note = for more information on function items, visit https://doc.rust-lang.org/reference/types/function-item.html - -hir_typeck_fru_expr = this expression does not end in a comma... -hir_typeck_fru_expr2 = ... so this is interpreted as a `..` range expression, instead of functional record update syntax -hir_typeck_fru_note = this expression may have been misinterpreted as a `..` range expression -hir_typeck_fru_suggestion = - to set the remaining fields{$expr -> - [NONE]{""} - *[other] {" "}from `{$expr}` - }, separate the last named field with a comma - -hir_typeck_functional_record_update_on_non_struct = - functional record update syntax requires a struct - -hir_typeck_gpu_kernel_abi_cannot_be_called = - functions with the "gpu-kernel" ABI cannot be called - .note = an `extern "gpu-kernel"` function must be launched on the GPU by the runtime - -hir_typeck_help_set_edition_cargo = set `edition = "{$edition}"` in `Cargo.toml` -hir_typeck_help_set_edition_standalone = pass `--edition {$edition}` to `rustc` - -hir_typeck_int_to_fat = cannot cast `{$expr_ty}` to a pointer that {$known_wide -> - [true] is - *[false] may be - } wide -hir_typeck_int_to_fat_label = creating a `{$cast_ty}` requires both an address and {$metadata} -hir_typeck_int_to_fat_label_nightly = consider casting this expression to `*const ()`, then using `core::ptr::from_raw_parts` - -hir_typeck_invalid_callee = expected function, found {$found} -hir_typeck_invalid_defined = `{$path}` defined here -hir_typeck_invalid_defined_kind = {$kind} `{$path}` defined here -hir_typeck_invalid_fn_defined = `{$func}` defined here returns `{$ty}` -hir_typeck_invalid_local = `{$local_name}` has type `{$ty}` - -hir_typeck_lossy_provenance_int2ptr = - strict provenance disallows casting integer `{$expr_ty}` to pointer `{$cast_ty}` - .suggestion = use `.with_addr()` to adjust a valid pointer in the same allocation, to this address - .help = if you can't comply with strict provenance and don't have a pointer with the correct provenance you can use `std::ptr::with_exposed_provenance()` instead - -hir_typeck_lossy_provenance_ptr2int = - under strict provenance it is considered bad style to cast pointer `{$expr_ty}` to integer `{$cast_ty}` - .suggestion = use `.addr()` to obtain the address of a pointer - .help = if you can't comply with strict provenance and need to expose the pointer provenance you can use `.expose_provenance()` instead - -hir_typeck_missing_parentheses_in_range = can't call method `{$method_name}` on type `{$ty}` - -hir_typeck_naked_asm_outside_naked_fn = - the `naked_asm!` macro can only be used in functions marked with `#[unsafe(naked)]` - -hir_typeck_naked_functions_asm_block = - naked functions must contain a single `naked_asm!` invocation - .label_multiple_asm = multiple `naked_asm!` invocations are not allowed in naked functions - .label_non_asm = not allowed in naked functions - -hir_typeck_naked_functions_must_naked_asm = - the `asm!` macro is not allowed in naked functions - .label = consider using the `naked_asm!` macro instead - -hir_typeck_never_type_fallback_flowing_into_unsafe_call = never type fallback affects this call to an `unsafe` function - .help = specify the type explicitly -hir_typeck_never_type_fallback_flowing_into_unsafe_deref = never type fallback affects this raw pointer dereference - .help = specify the type explicitly -hir_typeck_never_type_fallback_flowing_into_unsafe_method = never type fallback affects this call to an `unsafe` method - .help = specify the type explicitly -hir_typeck_never_type_fallback_flowing_into_unsafe_path = never type fallback affects this `unsafe` function - .help = specify the type explicitly -hir_typeck_never_type_fallback_flowing_into_unsafe_union_field = never type fallback affects this union access - .help = specify the type explicitly - -hir_typeck_no_associated_item = no {$item_kind} named `{$item_ident}` found for {$ty_prefix} `{$ty}`{$trait_missing_method -> - [true] {""} - *[other] {" "}in the current scope -} - -hir_typeck_no_field_on_type = no field `{$field}` on type `{$ty}` - -hir_typeck_no_field_on_variant = no field named `{$field}` on enum variant `{$container}::{$ident}` -hir_typeck_no_field_on_variant_enum = this enum variant... -hir_typeck_no_field_on_variant_field = ...does not have this field - -hir_typeck_no_patterns = - patterns not allowed in naked function parameters - -hir_typeck_note_caller_chooses_ty_for_ty_param = the caller chooses a type for `{$ty_param_name}` which can be different from `{$found_ty}` - -hir_typeck_note_edition_guide = for more on editions, read https://doc.rust-lang.org/edition-guide - -hir_typeck_option_result_asref = use `{$def_path}::as_ref` to convert `{$expected_ty}` to `{$expr_ty}` -hir_typeck_option_result_cloned = use `{$def_path}::cloned` to clone the value inside the `{$def_path}` -hir_typeck_option_result_copied = use `{$def_path}::copied` to copy the value inside the `{$def_path}` - -hir_typeck_outside_loop = - `{$name}` outside of a loop{$is_break -> - [true] {" or labeled block"} - *[false] {""} - } - .label = cannot `{$name}` outside of a loop{$is_break -> - [true] {" or labeled block"} - *[false] {""} - } - -hir_typeck_outside_loop_suggestion = consider labeling this block to be able to break within it - - -hir_typeck_params_not_allowed = - referencing function parameters is not allowed in naked functions - .help = follow the calling convention in asm block to use parameters - -hir_typeck_pass_to_variadic_function = can't pass `{$ty}` to variadic function - .suggestion = cast the value to `{$cast_ty}` - .teach_help = certain types, like `{$ty}`, must be cast before passing them to a variadic function to match the implicit cast that a C compiler would perform as part of C's numeric promotion rules - -hir_typeck_project_on_non_pin_project_type = cannot project on type that is not `#[pin_v2]` - .note = type defined here - .suggestion = add `#[pin_v2]` here - -hir_typeck_ptr_cast_add_auto_to_object = cannot add {$traits_len -> - [1] auto trait {$traits} - *[other] auto traits {$traits} -} to dyn bound via pointer cast - .note = this could allow UB elsewhere - .help = use `transmute` if you're sure this is sound - .label = unsupported cast - -hir_typeck_register_type_unstable = - type `{$ty}` cannot be used with this register class in stable - -hir_typeck_remove_semi_for_coerce = you might have meant to return the `match` expression -hir_typeck_remove_semi_for_coerce_expr = this could be implicitly returned but it is a statement, not a tail expression -hir_typeck_remove_semi_for_coerce_ret = the `match` arms can conform to this return type -hir_typeck_remove_semi_for_coerce_semi = the `match` is a statement because of this semicolon, consider removing it -hir_typeck_remove_semi_for_coerce_suggestion = remove this semicolon - -hir_typeck_replace_comma_with_semicolon = replace the comma with a semicolon to create {$descr} - -hir_typeck_return_stmt_outside_of_fn_body = - {$statement_kind} statement outside of function body - .encl_body_label = the {$statement_kind} is part of this body... - .encl_fn_label = ...not the enclosing function body - -hir_typeck_rpit_box_return_expr = if you change the return type to expect trait objects, box the returned expressions - -hir_typeck_rpit_change_return_type = you could change the return type to be a boxed trait object - -hir_typeck_rustcall_incorrect_args = - functions with the "rust-call" ABI must take a single non-self tuple argument - -hir_typeck_self_ctor_from_outer_item = can't reference `Self` constructor from outer item - .label = the inner item doesn't inherit generics from this impl, so `Self` is invalid to reference - .suggestion = replace `Self` with the actual type - -hir_typeck_self_ctor_from_outer_item_inner_item = `Self` used in this inner item - -hir_typeck_slicing_suggestion = consider slicing here - -hir_typeck_struct_expr_non_exhaustive = - cannot create non-exhaustive {$what} using struct expression - -hir_typeck_suggest_boxing_note = for more on the distinction between the stack and the heap, read https://doc.rust-lang.org/book/ch15-01-box.html, https://doc.rust-lang.org/rust-by-example/std/box.html, and https://doc.rust-lang.org/std/boxed/index.html - -hir_typeck_suggest_boxing_when_appropriate = store this in the heap by calling `Box::new` - -hir_typeck_suggest_ptr_null_mut = consider using `core::ptr::null_mut` instead - -hir_typeck_supertrait_item_multiple_shadowee = items from several supertraits are shadowed: {$traits} - -hir_typeck_supertrait_item_shadowee = item from `{$supertrait}` is shadowed by a subtrait item - -hir_typeck_supertrait_item_shadower = item from `{$subtrait}` shadows a supertrait item - -hir_typeck_supertrait_item_shadowing = trait item `{$item}` from `{$subtrait}` shadows identically named item from supertrait - -hir_typeck_trivial_cast = trivial {$numeric -> - [true] numeric cast - *[false] cast - }: `{$expr_ty}` as `{$cast_ty}` - .help = cast can be replaced by coercion; this might require a temporary variable - -hir_typeck_union_pat_dotdot = `..` cannot be used in union patterns - -hir_typeck_union_pat_multiple_fields = union patterns should have exactly one field - -hir_typeck_unlabeled_cf_in_while_condition = - `break` or `continue` with no label in the condition of a `while` loop - .label = unlabeled `{$cf_type}` in the condition of a `while` loop - -hir_typeck_unlabeled_in_labeled_block = - unlabeled `{$cf_type}` inside of a labeled block - .label = `{$cf_type}` statements that would diverge to or through a labeled block need to bear a label -hir_typeck_use_is_empty = - consider using the `is_empty` method on `{$expr_ty}` to determine if it contains anything - -hir_typeck_yield_expr_outside_of_coroutine = - yield expression outside of coroutine literal diff --git a/compiler/rustc_hir_typeck/src/callee.rs b/compiler/rustc_hir_typeck/src/callee.rs index a26b44e79dc7c..d04bd6f2295ae 100644 --- a/compiler/rustc_hir_typeck/src/callee.rs +++ b/compiler/rustc_hir_typeck/src/callee.rs @@ -2,7 +2,7 @@ use std::iter; use rustc_abi::{CanonAbi, ExternAbi}; use rustc_ast::util::parser::ExprPrecedence; -use rustc_errors::{Applicability, Diag, ErrorGuaranteed, StashKey}; +use rustc_errors::{Applicability, Diag, ErrorGuaranteed, StashKey, inline_fluent}; use rustc_hir::def::{self, CtorKind, Namespace, Res}; use rustc_hir::def_id::DefId; use rustc_hir::{self as hir, HirId, LangItem}; @@ -25,8 +25,8 @@ use tracing::{debug, instrument}; use super::method::MethodCallee; use super::method::probe::ProbeScope; use super::{Expectation, FnCtxt, TupleArgumentsFlag}; +use crate::errors; use crate::method::TreatNotYetDefinedOpaques; -use crate::{errors, fluent_generated}; /// Checks that it is legal to call methods of the trait corresponding /// to `trait_id` (this only cares about the trait, not the specific @@ -832,12 +832,12 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { (Some((_, kind, path)), _) => { err.arg("kind", kind); err.arg("path", path); - Some(fluent_generated::hir_typeck_invalid_defined_kind) + Some(inline_fluent!("{$kind} `{$path}` defined here")) } (_, Some(hir::QPath::Resolved(_, path))) => { self.tcx.sess.source_map().span_to_snippet(path.span).ok().map(|p| { err.arg("func", p); - fluent_generated::hir_typeck_invalid_fn_defined + inline_fluent!("`{$func}` defined here returns `{$ty}`") }) } _ => { @@ -846,15 +846,15 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { // type definitions themselves, but rather variables *of* that type. Res::Local(hir_id) => { err.arg("local_name", self.tcx.hir_name(hir_id)); - Some(fluent_generated::hir_typeck_invalid_local) + Some(inline_fluent!("`{$local_name}` has type `{$ty}`")) } Res::Def(kind, def_id) if kind.ns() == Some(Namespace::ValueNS) => { err.arg("path", self.tcx.def_path_str(def_id)); - Some(fluent_generated::hir_typeck_invalid_defined) + Some(inline_fluent!("`{$path}` defined here")) } _ => { err.arg("path", callee_ty); - Some(fluent_generated::hir_typeck_invalid_defined) + Some(inline_fluent!("`{$path}` defined here")) } } } diff --git a/compiler/rustc_hir_typeck/src/errors.rs b/compiler/rustc_hir_typeck/src/errors.rs index 0cf7f09e93767..0f330c3021c0f 100644 --- a/compiler/rustc_hir_typeck/src/errors.rs +++ b/compiler/rustc_hir_typeck/src/errors.rs @@ -7,7 +7,7 @@ use rustc_ast::{AssignOpKind, Label}; use rustc_errors::codes::*; use rustc_errors::{ Applicability, Diag, DiagArgValue, DiagCtxtHandle, DiagSymbolList, Diagnostic, - EmissionGuarantee, IntoDiagArg, Level, MultiSpan, Subdiagnostic, + EmissionGuarantee, IntoDiagArg, Level, MultiSpan, Subdiagnostic, inline_fluent, }; use rustc_hir as hir; use rustc_hir::ExprKind; @@ -17,15 +17,15 @@ use rustc_span::edition::{Edition, LATEST_STABLE_EDITION}; use rustc_span::source_map::Spanned; use rustc_span::{Ident, Span, Symbol}; -use crate::{FnCtxt, fluent_generated as fluent}; +use crate::FnCtxt; #[derive(Diagnostic)] -#[diag(hir_typeck_base_expression_double_dot, code = E0797)] +#[diag("base expression required after `..`", code = E0797)] pub(crate) struct BaseExpressionDoubleDot { #[primary_span] pub span: Span, #[suggestion( - hir_typeck_base_expression_double_dot_enable_default_field_values, + "add `#![feature(default_field_values)]` to the crate attributes to enable default values on `struct` fields", code = "#![feature(default_field_values)]\n", applicability = "machine-applicable", style = "verbose" @@ -39,7 +39,7 @@ pub(crate) struct BaseExpressionDoubleDot { #[derive(Subdiagnostic)] #[suggestion( - hir_typeck_base_expression_double_dot_remove, + "remove the `..` as all the fields are already present", code = "", applicability = "machine-applicable", style = "verbose" @@ -51,7 +51,7 @@ pub(crate) struct BaseExpressionDoubleDotRemove { #[derive(Subdiagnostic)] #[suggestion( - hir_typeck_base_expression_double_dot_add_expr, + "add a base expression here", code = "/* expr */", applicability = "has-placeholders", style = "verbose" @@ -62,24 +62,24 @@ pub(crate) struct BaseExpressionDoubleDotAddExpr { } #[derive(Diagnostic)] -#[diag(hir_typeck_field_multiply_specified_in_initializer, code = E0062)] +#[diag("field `{$ident}` specified more than once", code = E0062)] pub(crate) struct FieldMultiplySpecifiedInInitializer { #[primary_span] - #[label] + #[label("used more than once")] pub span: Span, - #[label(hir_typeck_previous_use_label)] + #[label("first use of `{$ident}`")] pub prev_span: Span, pub ident: Ident, } #[derive(Diagnostic)] -#[diag(hir_typeck_return_stmt_outside_of_fn_body, code = E0572)] +#[diag("{$statement_kind} statement outside of function body", code = E0572)] pub(crate) struct ReturnStmtOutsideOfFnBody { #[primary_span] pub span: Span, - #[label(hir_typeck_encl_body_label)] + #[label("the {$statement_kind} is part of this body...")] pub encl_body_span: Option, - #[label(hir_typeck_encl_fn_label)] + #[label("...not the enclosing function body")] pub encl_fn_span: Option, pub statement_kind: ReturnLikeStatementKind, } @@ -102,21 +102,21 @@ impl IntoDiagArg for ReturnLikeStatementKind { } #[derive(Diagnostic)] -#[diag(hir_typeck_rustcall_incorrect_args)] +#[diag("functions with the \"rust-call\" ABI must take a single non-self tuple argument")] pub(crate) struct RustCallIncorrectArgs { #[primary_span] pub span: Span, } #[derive(Diagnostic)] -#[diag(hir_typeck_yield_expr_outside_of_coroutine, code = E0627)] +#[diag("yield expression outside of coroutine literal", code = E0627)] pub(crate) struct YieldExprOutsideOfCoroutine { #[primary_span] pub span: Span, } #[derive(Diagnostic)] -#[diag(hir_typeck_struct_expr_non_exhaustive, code = E0639)] +#[diag("cannot create non-exhaustive {$what} using struct expression", code = E0639)] pub(crate) struct StructExprNonExhaustive { #[primary_span] pub span: Span, @@ -124,24 +124,24 @@ pub(crate) struct StructExprNonExhaustive { } #[derive(Diagnostic)] -#[diag(hir_typeck_functional_record_update_on_non_struct, code = E0436)] +#[diag("functional record update syntax requires a struct", code = E0436)] pub(crate) struct FunctionalRecordUpdateOnNonStruct { #[primary_span] pub span: Span, } #[derive(Diagnostic)] -#[diag(hir_typeck_address_of_temporary_taken, code = E0745)] +#[diag("cannot take address of a temporary", code = E0745)] pub(crate) struct AddressOfTemporaryTaken { #[primary_span] - #[label] + #[label("temporary value")] pub span: Span, } #[derive(Subdiagnostic)] pub(crate) enum AddReturnTypeSuggestion { #[suggestion( - hir_typeck_add_return_type_add, + "try adding a return type", code = " -> {found}", applicability = "machine-applicable" )] @@ -151,7 +151,7 @@ pub(crate) enum AddReturnTypeSuggestion { found: String, }, #[suggestion( - hir_typeck_add_return_type_missing_here, + "a return type might be missing here", code = " -> _", applicability = "has-placeholders" )] @@ -163,12 +163,12 @@ pub(crate) enum AddReturnTypeSuggestion { #[derive(Subdiagnostic)] pub(crate) enum ExpectedReturnTypeLabel<'tcx> { - #[label(hir_typeck_expected_default_return_type)] + #[label("expected `()` because of default return type")] Unit { #[primary_span] span: Span, }, - #[label(hir_typeck_expected_return_type)] + #[label("expected `{$expected}` because of return type")] Other { #[primary_span] span: Span, @@ -177,10 +177,10 @@ pub(crate) enum ExpectedReturnTypeLabel<'tcx> { } #[derive(Diagnostic)] -#[diag(hir_typeck_explicit_destructor, code = E0040)] +#[diag("explicit use of destructor method", code = E0040)] pub(crate) struct ExplicitDestructorCall { #[primary_span] - #[label] + #[label("explicit destructor calls not allowed")] pub span: Span, #[subdiagnostic] pub sugg: ExplicitDestructorCallSugg, @@ -188,9 +188,13 @@ pub(crate) struct ExplicitDestructorCall { #[derive(Subdiagnostic)] pub(crate) enum ExplicitDestructorCallSugg { - #[suggestion(hir_typeck_suggestion, code = "drop", applicability = "maybe-incorrect")] + #[suggestion( + "consider using `drop` function", + code = "drop", + applicability = "maybe-incorrect" + )] Empty(#[primary_span] Span), - #[multipart_suggestion(hir_typeck_suggestion, style = "short")] + #[multipart_suggestion("consider using `drop` function", style = "short")] Snippet { #[suggestion_part(code = "drop(")] lo: Span, @@ -200,10 +204,10 @@ pub(crate) enum ExplicitDestructorCallSugg { } #[derive(Diagnostic)] -#[diag(hir_typeck_missing_parentheses_in_range, code = E0689)] +#[diag("can't call method `{$method_name}` on type `{$ty}`", code = E0689)] pub(crate) struct MissingParenthesesInRange<'tcx> { #[primary_span] - #[label(hir_typeck_missing_parentheses_in_range)] + #[label("can't call method `{$method_name}` on type `{$ty}`")] pub span: Span, pub ty: Ty<'tcx>, pub method_name: String, @@ -213,32 +217,32 @@ pub(crate) struct MissingParenthesesInRange<'tcx> { #[derive(LintDiagnostic)] pub(crate) enum NeverTypeFallbackFlowingIntoUnsafe { - #[help] - #[diag(hir_typeck_never_type_fallback_flowing_into_unsafe_call)] + #[help("specify the type explicitly")] + #[diag("never type fallback affects this call to an `unsafe` function")] Call { #[subdiagnostic] sugg: SuggestAnnotations, }, - #[help] - #[diag(hir_typeck_never_type_fallback_flowing_into_unsafe_method)] + #[help("specify the type explicitly")] + #[diag("never type fallback affects this call to an `unsafe` method")] Method { #[subdiagnostic] sugg: SuggestAnnotations, }, - #[help] - #[diag(hir_typeck_never_type_fallback_flowing_into_unsafe_path)] + #[help("specify the type explicitly")] + #[diag("never type fallback affects this `unsafe` function")] Path { #[subdiagnostic] sugg: SuggestAnnotations, }, - #[help] - #[diag(hir_typeck_never_type_fallback_flowing_into_unsafe_union_field)] + #[help("specify the type explicitly")] + #[diag("never type fallback affects this union access")] UnionField { #[subdiagnostic] sugg: SuggestAnnotations, }, - #[help] - #[diag(hir_typeck_never_type_fallback_flowing_into_unsafe_deref)] + #[help("specify the type explicitly")] + #[diag("never type fallback affects this raw pointer dereference")] Deref { #[subdiagnostic] sugg: SuggestAnnotations, @@ -246,10 +250,10 @@ pub(crate) enum NeverTypeFallbackFlowingIntoUnsafe { } #[derive(LintDiagnostic)] -#[help] -#[diag(hir_typeck_dependency_on_unit_never_type_fallback)] +#[help("specify the types explicitly")] +#[diag("this function depends on never type fallback being `()`")] pub(crate) struct DependencyOnUnitNeverTypeFallback<'tcx> { - #[note] + #[note("in edition 2024, the requirement `{$obligation}` will fail")] pub obligation_span: Span, pub obligation: ty::Predicate<'tcx>, #[subdiagnostic] @@ -310,7 +314,7 @@ impl Subdiagnostic for SuggestAnnotations { #[derive(Subdiagnostic)] #[multipart_suggestion( - hir_typeck_add_missing_parentheses_in_range, + "you must surround the range in parentheses to call its `{$func_name}` function", style = "verbose", applicability = "maybe-incorrect" )] @@ -337,17 +341,35 @@ impl Subdiagnostic for TypeMismatchFruTypo { // Only explain that `a ..b` is a range if it's split up if self.expr_span.between(self.fru_span).is_empty() { - diag.span_note(self.expr_span.to(self.fru_span), fluent::hir_typeck_fru_note); + diag.span_note( + self.expr_span.to(self.fru_span), + inline_fluent!( + "this expression may have been misinterpreted as a `..` range expression" + ), + ); } else { let mut multispan: MultiSpan = vec![self.expr_span, self.fru_span].into(); - multispan.push_span_label(self.expr_span, fluent::hir_typeck_fru_expr); - multispan.push_span_label(self.fru_span, fluent::hir_typeck_fru_expr2); - diag.span_note(multispan, fluent::hir_typeck_fru_note); + multispan.push_span_label( + self.expr_span, + inline_fluent!("this expression does not end in a comma..."), + ); + multispan.push_span_label(self.fru_span, inline_fluent!("... so this is interpreted as a `..` range expression, instead of functional record update syntax")); + diag.span_note( + multispan, + inline_fluent!( + "this expression may have been misinterpreted as a `..` range expression" + ), + ); } diag.span_suggestion( self.expr_span.shrink_to_hi(), - fluent::hir_typeck_fru_suggestion, + inline_fluent!( + "to set the remaining fields{$expr -> + [NONE]{\"\"} + *[other] {\" \"}from `{$expr}` + }, separate the last named field with a comma" + ), ", ", Applicability::MaybeIncorrect, ); @@ -355,8 +377,10 @@ impl Subdiagnostic for TypeMismatchFruTypo { } #[derive(LintDiagnostic)] -#[diag(hir_typeck_lossy_provenance_int2ptr)] -#[help] +#[diag("strict provenance disallows casting integer `{$expr_ty}` to pointer `{$cast_ty}`")] +#[help( + "if you can't comply with strict provenance and don't have a pointer with the correct provenance you can use `std::ptr::with_exposed_provenance()` instead" +)] pub(crate) struct LossyProvenanceInt2Ptr<'tcx> { pub expr_ty: Ty<'tcx>, pub cast_ty: Ty<'tcx>, @@ -365,19 +389,25 @@ pub(crate) struct LossyProvenanceInt2Ptr<'tcx> { } #[derive(Diagnostic)] -#[diag(hir_typeck_ptr_cast_add_auto_to_object, code = E0804)] -#[note] -#[help] +#[diag("cannot add {$traits_len -> + [1] auto trait {$traits} + *[other] auto traits {$traits} +} to dyn bound via pointer cast", code = E0804)] +#[note("this could allow UB elsewhere")] +#[help("use `transmute` if you're sure this is sound")] pub(crate) struct PtrCastAddAutoToObject { #[primary_span] - #[label] + #[label("unsupported cast")] pub span: Span, pub traits_len: usize, pub traits: DiagSymbolList, } #[derive(Subdiagnostic)] -#[multipart_suggestion(hir_typeck_suggestion, applicability = "has-placeholders")] +#[multipart_suggestion( + "use `.with_addr()` to adjust a valid pointer in the same allocation, to this address", + applicability = "has-placeholders" +)] pub(crate) struct LossyProvenanceInt2PtrSuggestion { #[suggestion_part(code = "(...).with_addr(")] pub lo: Span, @@ -386,8 +416,12 @@ pub(crate) struct LossyProvenanceInt2PtrSuggestion { } #[derive(LintDiagnostic)] -#[diag(hir_typeck_lossy_provenance_ptr2int)] -#[help] +#[diag( + "under strict provenance it is considered bad style to cast pointer `{$expr_ty}` to integer `{$cast_ty}`" +)] +#[help( + "if you can't comply with strict provenance and need to expose the pointer provenance you can use `.expose_provenance()` instead" +)] pub(crate) struct LossyProvenancePtr2Int<'tcx> { pub expr_ty: Ty<'tcx>, pub cast_ty: Ty<'tcx>, @@ -397,7 +431,10 @@ pub(crate) struct LossyProvenancePtr2Int<'tcx> { #[derive(Subdiagnostic)] pub(crate) enum LossyProvenancePtr2IntSuggestion<'tcx> { - #[multipart_suggestion(hir_typeck_suggestion, applicability = "maybe-incorrect")] + #[multipart_suggestion( + "use `.addr()` to obtain the address of a pointer", + applicability = "maybe-incorrect" + )] NeedsParensCast { #[suggestion_part(code = "(")] expr_span: Span, @@ -405,7 +442,10 @@ pub(crate) enum LossyProvenancePtr2IntSuggestion<'tcx> { cast_span: Span, cast_ty: Ty<'tcx>, }, - #[multipart_suggestion(hir_typeck_suggestion, applicability = "maybe-incorrect")] + #[multipart_suggestion( + "use `.addr()` to obtain the address of a pointer", + applicability = "maybe-incorrect" + )] NeedsParens { #[suggestion_part(code = "(")] expr_span: Span, @@ -413,7 +453,7 @@ pub(crate) enum LossyProvenancePtr2IntSuggestion<'tcx> { cast_span: Span, }, #[suggestion( - hir_typeck_suggestion, + "use `.addr()` to obtain the address of a pointer", code = ".addr() as {cast_ty}", applicability = "maybe-incorrect" )] @@ -422,7 +462,11 @@ pub(crate) enum LossyProvenancePtr2IntSuggestion<'tcx> { cast_span: Span, cast_ty: Ty<'tcx>, }, - #[suggestion(hir_typeck_suggestion, code = ".addr()", applicability = "maybe-incorrect")] + #[suggestion( + "use `.addr()` to obtain the address of a pointer", + code = ".addr()", + applicability = "maybe-incorrect" + )] Other { #[primary_span] cast_span: Span, @@ -431,11 +475,11 @@ pub(crate) enum LossyProvenancePtr2IntSuggestion<'tcx> { #[derive(Subdiagnostic)] pub(crate) enum HelpUseLatestEdition { - #[help(hir_typeck_help_set_edition_cargo)] - #[note(hir_typeck_note_edition_guide)] + #[help("set `edition = \"{$edition}\"` in `Cargo.toml`")] + #[note("for more on editions, read https://doc.rust-lang.org/edition-guide")] Cargo { edition: Edition }, - #[help(hir_typeck_help_set_edition_standalone)] - #[note(hir_typeck_note_edition_guide)] + #[help("pass `--edition {$edition}` to `rustc`")] + #[note("for more on editions, read https://doc.rust-lang.org/edition-guide")] Standalone { edition: Edition }, } @@ -451,7 +495,7 @@ impl HelpUseLatestEdition { } #[derive(Diagnostic)] -#[diag(hir_typeck_no_field_on_type, code = E0609)] +#[diag("no field `{$field}` on type `{$ty}`", code = E0609)] pub(crate) struct NoFieldOnType<'tcx> { #[primary_span] pub(crate) span: Span, @@ -460,33 +504,33 @@ pub(crate) struct NoFieldOnType<'tcx> { } #[derive(Diagnostic)] -#[diag(hir_typeck_no_field_on_variant, code = E0609)] +#[diag("no field named `{$field}` on enum variant `{$container}::{$ident}`", code = E0609)] pub(crate) struct NoFieldOnVariant<'tcx> { #[primary_span] pub(crate) span: Span, pub(crate) container: Ty<'tcx>, pub(crate) ident: Ident, pub(crate) field: Ident, - #[label(hir_typeck_no_field_on_variant_enum)] + #[label("this enum variant...")] pub(crate) enum_span: Span, - #[label(hir_typeck_no_field_on_variant_field)] + #[label("...does not have this field")] pub(crate) field_span: Span, } #[derive(Diagnostic)] -#[diag(hir_typeck_cant_dereference, code = E0614)] +#[diag("type `{$ty}` cannot be dereferenced", code = E0614)] pub(crate) struct CantDereference<'tcx> { #[primary_span] - #[label(hir_typeck_cant_dereference_label)] + #[label("can't be dereferenced")] pub(crate) span: Span, pub(crate) ty: Ty<'tcx>, } #[derive(Diagnostic)] -#[diag(hir_typeck_expected_array_or_slice, code = E0529)] +#[diag("expected an array or slice, found `{$ty}`", code = E0529)] pub(crate) struct ExpectedArrayOrSlice<'tcx> { #[primary_span] - #[label(hir_typeck_expected_array_or_slice_label)] + #[label("pattern cannot match with input type `{$ty}`")] pub(crate) span: Span, pub(crate) ty: Ty<'tcx>, pub(crate) slice_pat_semantics: bool, @@ -498,7 +542,7 @@ pub(crate) struct ExpectedArrayOrSlice<'tcx> { #[derive(Subdiagnostic)] #[suggestion( - hir_typeck_as_deref_suggestion, + "consider using `as_deref` here", code = ".as_deref()", style = "verbose", applicability = "maybe-incorrect" @@ -510,7 +554,7 @@ pub(crate) struct AsDerefSuggestion { #[derive(Subdiagnostic)] #[suggestion( - hir_typeck_slicing_suggestion, + "consider slicing here", code = "[..]", style = "verbose", applicability = "maybe-incorrect" @@ -521,7 +565,7 @@ pub(crate) struct SlicingSuggestion { } #[derive(Diagnostic)] -#[diag(hir_typeck_invalid_callee, code = E0618)] +#[diag("expected function, found {$found}", code = E0618)] pub(crate) struct InvalidCallee<'tcx> { #[primary_span] pub span: Span, @@ -530,15 +574,20 @@ pub(crate) struct InvalidCallee<'tcx> { } #[derive(Diagnostic)] -#[diag(hir_typeck_int_to_fat, code = E0606)] +#[diag("cannot cast `{$expr_ty}` to a pointer that {$known_wide -> + [true] is + *[false] may be +} wide", code = E0606)] pub(crate) struct IntToWide<'tcx> { #[primary_span] - #[label(hir_typeck_int_to_fat_label)] + #[label("creating a `{$cast_ty}` requires both an address and {$metadata}")] pub span: Span, pub metadata: &'tcx str, pub expr_ty: Ty<'tcx>, pub cast_ty: Ty<'tcx>, - #[label(hir_typeck_int_to_fat_label_nightly)] + #[label( + "consider casting this expression to `*const ()`, then using `core::ptr::from_raw_parts`" + )] pub expr_if_nightly: Option, pub known_wide: bool, } @@ -546,7 +595,7 @@ pub(crate) struct IntToWide<'tcx> { #[derive(Subdiagnostic)] pub(crate) enum OptionResultRefMismatch { #[suggestion( - hir_typeck_option_result_copied, + "use `{$def_path}::copied` to copy the value inside the `{$def_path}`", code = ".copied()", style = "verbose", applicability = "machine-applicable" @@ -557,7 +606,7 @@ pub(crate) enum OptionResultRefMismatch { def_path: String, }, #[suggestion( - hir_typeck_option_result_cloned, + "use `{$def_path}::cloned` to clone the value inside the `{$def_path}`", code = ".cloned()", style = "verbose", applicability = "machine-applicable" @@ -569,7 +618,7 @@ pub(crate) enum OptionResultRefMismatch { }, // FIXME: #114050 // #[suggestion( - // hir_typeck_option_result_asref, + // "use `{$def_path}::as_ref` to convert `{$expected_ty}` to `{$expr_ty}`", // code = ".as_ref()", // style = "verbose", // applicability = "machine-applicable" @@ -592,14 +641,30 @@ pub(crate) struct RemoveSemiForCoerce { impl Subdiagnostic for RemoveSemiForCoerce { fn add_to_diag(self, diag: &mut Diag<'_, G>) { let mut multispan: MultiSpan = self.semi.into(); - multispan.push_span_label(self.expr, fluent::hir_typeck_remove_semi_for_coerce_expr); - multispan.push_span_label(self.ret, fluent::hir_typeck_remove_semi_for_coerce_ret); - multispan.push_span_label(self.semi, fluent::hir_typeck_remove_semi_for_coerce_semi); - diag.span_note(multispan, fluent::hir_typeck_remove_semi_for_coerce); + multispan.push_span_label( + self.expr, + inline_fluent!( + "this could be implicitly returned but it is a statement, not a tail expression" + ), + ); + multispan.push_span_label( + self.ret, + inline_fluent!("the `match` arms can conform to this return type"), + ); + multispan.push_span_label( + self.semi, + inline_fluent!( + "the `match` is a statement because of this semicolon, consider removing it" + ), + ); + diag.span_note( + multispan, + inline_fluent!("you might have meant to return the `match` expression"), + ); diag.tool_only_span_suggestion( self.semi, - fluent::hir_typeck_remove_semi_for_coerce_suggestion, + inline_fluent!("remove this semicolon"), "", Applicability::MaybeIncorrect, ); @@ -607,14 +672,14 @@ impl Subdiagnostic for RemoveSemiForCoerce { } #[derive(Diagnostic)] -#[diag(hir_typeck_union_pat_multiple_fields)] +#[diag("union patterns should have exactly one field")] pub(crate) struct UnionPatMultipleFields { #[primary_span] pub span: Span, } #[derive(Diagnostic)] -#[diag(hir_typeck_union_pat_dotdot)] +#[diag("`..` cannot be used in union patterns")] pub(crate) struct UnionPatDotDot { #[primary_span] pub span: Span, @@ -622,7 +687,7 @@ pub(crate) struct UnionPatDotDot { #[derive(Subdiagnostic)] #[multipart_suggestion( - hir_typeck_use_is_empty, + "consider using the `is_empty` method on `{$expr_ty}` to determine if it contains anything", applicability = "maybe-incorrect", style = "verbose" )] @@ -635,7 +700,7 @@ pub(crate) struct UseIsEmpty<'tcx> { } #[derive(Diagnostic)] -#[diag(hir_typeck_arg_mismatch_indeterminate)] +#[diag("argument type mismatch was detected, but rustc had trouble determining where")] pub(crate) struct ArgMismatchIndeterminate { #[primary_span] pub span: Span, @@ -643,9 +708,11 @@ pub(crate) struct ArgMismatchIndeterminate { #[derive(Subdiagnostic)] pub(crate) enum SuggestBoxing { - #[note(hir_typeck_suggest_boxing_note)] + #[note( + "for more on the distinction between the stack and the heap, read https://doc.rust-lang.org/book/ch15-01-box.html, https://doc.rust-lang.org/rust-by-example/std/box.html, and https://doc.rust-lang.org/std/boxed/index.html" + )] #[multipart_suggestion( - hir_typeck_suggest_boxing_when_appropriate, + "store this in the heap by calling `Box::new`", applicability = "machine-applicable" )] Unit { @@ -654,11 +721,15 @@ pub(crate) enum SuggestBoxing { #[suggestion_part(code = "")] end: Span, }, - #[note(hir_typeck_suggest_boxing_note)] + #[note( + "for more on the distinction between the stack and the heap, read https://doc.rust-lang.org/book/ch15-01-box.html, https://doc.rust-lang.org/rust-by-example/std/box.html, and https://doc.rust-lang.org/std/boxed/index.html" + )] AsyncBody, - #[note(hir_typeck_suggest_boxing_note)] + #[note( + "for more on the distinction between the stack and the heap, read https://doc.rust-lang.org/book/ch15-01-box.html, https://doc.rust-lang.org/rust-by-example/std/box.html, and https://doc.rust-lang.org/std/boxed/index.html" + )] #[multipart_suggestion( - hir_typeck_suggest_boxing_when_appropriate, + "store this in the heap by calling `Box::new`", applicability = "machine-applicable" )] ExprFieldShorthand { @@ -668,9 +739,11 @@ pub(crate) enum SuggestBoxing { end: Span, ident: Ident, }, - #[note(hir_typeck_suggest_boxing_note)] + #[note( + "for more on the distinction between the stack and the heap, read https://doc.rust-lang.org/book/ch15-01-box.html, https://doc.rust-lang.org/rust-by-example/std/box.html, and https://doc.rust-lang.org/std/boxed/index.html" + )] #[multipart_suggestion( - hir_typeck_suggest_boxing_when_appropriate, + "store this in the heap by calling `Box::new`", applicability = "machine-applicable" )] Other { @@ -683,7 +756,7 @@ pub(crate) enum SuggestBoxing { #[derive(Subdiagnostic)] #[suggestion( - hir_typeck_suggest_ptr_null_mut, + "consider using `core::ptr::null_mut` instead", applicability = "maybe-incorrect", style = "verbose", code = "core::ptr::null_mut()" @@ -694,8 +767,13 @@ pub(crate) struct SuggestPtrNullMut { } #[derive(LintDiagnostic)] -#[diag(hir_typeck_trivial_cast)] -#[help] +#[diag( + "trivial {$numeric -> + [true] numeric cast + *[false] cast + }: `{$expr_ty}` as `{$cast_ty}`" +)] +#[help("cast can be replaced by coercion; this might require a temporary variable")] pub(crate) struct TrivialCast<'tcx> { pub numeric: bool, pub expr_ty: Ty<'tcx>, @@ -716,17 +794,24 @@ pub(crate) struct BreakNonLoop<'a> { impl<'a, G: EmissionGuarantee> Diagnostic<'_, G> for BreakNonLoop<'a> { #[track_caller] fn into_diag(self, dcx: DiagCtxtHandle<'_>, level: Level) -> Diag<'_, G> { - let mut diag = Diag::new(dcx, level, fluent::hir_typeck_break_non_loop); + let mut diag = + Diag::new(dcx, level, inline_fluent!("`break` with value from a `{$kind}` loop")); diag.span(self.span); diag.code(E0571); diag.arg("kind", self.kind); - diag.span_label(self.span, fluent::hir_typeck_label); + diag.span_label( + self.span, + inline_fluent!("can only break with a value inside `loop` or breakable block"), + ); if let Some(head) = self.head { - diag.span_label(head, fluent::hir_typeck_label2); + diag.span_label( + head, + inline_fluent!("you can't `break` with a value in a `{$kind}` loop"), + ); } diag.span_suggestion( self.span, - fluent::hir_typeck_suggestion, + inline_fluent!("use `break` on its own without a value inside this `{$kind}` loop"), self.suggestion, Applicability::MaybeIncorrect, ); @@ -744,7 +829,9 @@ impl<'a, G: EmissionGuarantee> Diagnostic<'_, G> for BreakNonLoop<'a> { _ => { diag.span_suggestion( self.break_expr_span, - fluent::hir_typeck_break_expr_suggestion, + inline_fluent!( + "alternatively, you might have meant to use the available loop label" + ), label.ident, Applicability::MaybeIncorrect, ); @@ -756,33 +843,33 @@ impl<'a, G: EmissionGuarantee> Diagnostic<'_, G> for BreakNonLoop<'a> { } #[derive(Diagnostic)] -#[diag(hir_typeck_continue_labeled_block, code = E0696)] +#[diag("`continue` pointing to a labeled block", code = E0696)] pub(crate) struct ContinueLabeledBlock { #[primary_span] - #[label] + #[label("labeled blocks cannot be `continue`'d")] pub span: Span, - #[label(hir_typeck_block_label)] + #[label("labeled block the `continue` points to")] pub block_span: Span, } #[derive(Diagnostic)] -#[diag(hir_typeck_break_inside_closure, code = E0267)] +#[diag("`{$name}` inside of a closure", code = E0267)] pub(crate) struct BreakInsideClosure<'a> { #[primary_span] - #[label] + #[label("cannot `{$name}` inside of a closure")] pub span: Span, - #[label(hir_typeck_closure_label)] + #[label("enclosing closure")] pub closure_span: Span, pub name: &'a str, } #[derive(Diagnostic)] -#[diag(hir_typeck_break_inside_coroutine, code = E0267)] +#[diag("`{$name}` inside `{$kind}` {$source}", code = E0267)] pub(crate) struct BreakInsideCoroutine<'a> { #[primary_span] - #[label] + #[label("cannot `{$name}` inside `{$kind}` {$source}")] pub span: Span, - #[label(hir_typeck_coroutine_label)] + #[label("enclosing `{$kind}` {$source}")] pub coroutine_span: Span, pub name: &'a str, pub kind: &'a str, @@ -790,10 +877,18 @@ pub(crate) struct BreakInsideCoroutine<'a> { } #[derive(Diagnostic)] -#[diag(hir_typeck_outside_loop, code = E0268)] +#[diag("`{$name}` outside of a loop{$is_break -> + [true] {\" or labeled block\"} + *[false] {\"\"} + }", code = E0268)] pub(crate) struct OutsideLoop<'a> { #[primary_span] - #[label] + #[label( + "cannot `{$name}` outside of a loop{$is_break -> + [true] {\" or labeled block\"} + *[false] {\"\"} + }" + )] pub spans: Vec, pub name: &'a str, pub is_break: bool, @@ -801,7 +896,10 @@ pub(crate) struct OutsideLoop<'a> { pub suggestion: Option, } #[derive(Subdiagnostic)] -#[multipart_suggestion(hir_typeck_outside_loop_suggestion, applicability = "maybe-incorrect")] +#[multipart_suggestion( + "consider labeling this block to be able to break within it", + applicability = "maybe-incorrect" +)] pub(crate) struct OutsideLoopSuggestion { #[suggestion_part(code = "'block: ")] pub block_span: Span, @@ -810,25 +908,30 @@ pub(crate) struct OutsideLoopSuggestion { } #[derive(Diagnostic)] -#[diag(hir_typeck_unlabeled_in_labeled_block, code = E0695)] +#[diag("unlabeled `{$cf_type}` inside of a labeled block", code = E0695)] pub(crate) struct UnlabeledInLabeledBlock<'a> { #[primary_span] - #[label] + #[label( + "`{$cf_type}` statements that would diverge to or through a labeled block need to bear a label" + )] pub span: Span, pub cf_type: &'a str, } #[derive(Diagnostic)] -#[diag(hir_typeck_unlabeled_cf_in_while_condition, code = E0590)] +#[diag("`break` or `continue` with no label in the condition of a `while` loop", code = E0590)] pub(crate) struct UnlabeledCfInWhileCondition<'a> { #[primary_span] - #[label] + #[label("unlabeled `{$cf_type}` in the condition of a `while` loop")] pub span: Span, pub cf_type: &'a str, } #[derive(Diagnostic)] -#[diag(hir_typeck_no_associated_item, code = E0599)] +#[diag("no {$item_kind} named `{$item_ident}` found for {$ty_prefix} `{$ty}`{$trait_missing_method -> + [true] {\"\"} + *[other] {\" \"}in the current scope +}", code = E0599)] pub(crate) struct NoAssociatedItem<'tcx> { #[primary_span] pub span: Span, @@ -840,7 +943,13 @@ pub(crate) struct NoAssociatedItem<'tcx> { } #[derive(Subdiagnostic)] -#[note(hir_typeck_candidate_trait_note)] +#[note( + "`{$trait_name}` defines an item `{$item_name}`{$action_or_ty -> + [NONE] {\"\"} + [implement] , perhaps you need to implement it + *[other] , perhaps you need to restrict type parameter `{$action_or_ty}` with it + }" +)] pub(crate) struct CandidateTraitNote { #[primary_span] pub span: Span, @@ -850,7 +959,7 @@ pub(crate) struct CandidateTraitNote { } #[derive(Diagnostic)] -#[diag(hir_typeck_cannot_cast_to_bool, code = E0054)] +#[diag("cannot cast `{$expr_ty}` as `bool`", code = E0054)] pub(crate) struct CannotCastToBool<'tcx> { #[primary_span] pub span: Span, @@ -860,7 +969,7 @@ pub(crate) struct CannotCastToBool<'tcx> { } #[derive(Diagnostic)] -#[diag(hir_typeck_cast_enum_drop)] +#[diag("cannot cast enum `{$expr_ty}` into integer `{$cast_ty}` because it implements `Drop`")] pub(crate) struct CastEnumDrop<'tcx> { #[primary_span] pub span: Span, @@ -869,7 +978,10 @@ pub(crate) struct CastEnumDrop<'tcx> { } #[derive(Diagnostic)] -#[diag(hir_typeck_cast_unknown_pointer, code = E0641)] +#[diag("cannot cast {$to -> + [true] to + *[false] from +} a pointer of an unknown kind", code = E0641)] pub(crate) struct CastUnknownPointer { #[primary_span] pub span: Span, @@ -887,13 +999,13 @@ impl rustc_errors::Subdiagnostic for CastUnknownPointerSub { fn add_to_diag(self, diag: &mut Diag<'_, G>) { match self { CastUnknownPointerSub::To(span) => { - let msg = diag.eagerly_translate(fluent::hir_typeck_label_to); + let msg = diag.eagerly_translate(inline_fluent!("needs more type information")); diag.span_label(span, msg); - let msg = diag.eagerly_translate(fluent::hir_typeck_note); + let msg = diag.eagerly_translate(inline_fluent!("the type information given here is insufficient to check whether the pointer cast is valid")); diag.note(msg); } CastUnknownPointerSub::From(span) => { - let msg = diag.eagerly_translate(fluent::hir_typeck_label_from); + let msg = diag.eagerly_translate(inline_fluent!("the type information given here is insufficient to check whether the pointer cast is valid")); diag.span_label(span, msg); } } @@ -903,18 +1015,18 @@ impl rustc_errors::Subdiagnostic for CastUnknownPointerSub { #[derive(Subdiagnostic)] pub(crate) enum CannotCastToBoolHelp { #[suggestion( - hir_typeck_suggestion, + "compare with zero instead", applicability = "machine-applicable", code = " != 0", style = "verbose" )] Numeric(#[primary_span] Span), - #[label(hir_typeck_label)] + #[label("unsupported cast")] Unsupported(#[primary_span] Span), } #[derive(Diagnostic)] -#[diag(hir_typeck_ctor_is_private, code = E0603)] +#[diag("tuple struct constructor `{$def}` is private", code = E0603)] pub(crate) struct CtorIsPrivate { #[primary_span] pub span: Span, @@ -922,7 +1034,7 @@ pub(crate) struct CtorIsPrivate { } #[derive(Subdiagnostic)] -#[note(hir_typeck_deref_is_empty)] +#[note("this expression `Deref`s to `{$deref_ty}` which implements `is_empty`")] pub(crate) struct DerefImplsIsEmpty<'tcx> { #[primary_span] pub span: Span, @@ -931,7 +1043,7 @@ pub(crate) struct DerefImplsIsEmpty<'tcx> { #[derive(Subdiagnostic)] #[multipart_suggestion( - hir_typeck_convert_using_method, + "try using `{$sugg}` to convert `{$found}` to `{$expected}`", applicability = "machine-applicable", style = "verbose" )] @@ -946,7 +1058,9 @@ pub(crate) struct SuggestConvertViaMethod<'tcx> { } #[derive(Subdiagnostic)] -#[note(hir_typeck_note_caller_chooses_ty_for_ty_param)] +#[note( + "the caller chooses a type for `{$ty_param_name}` which can be different from `{$found_ty}`" +)] pub(crate) struct NoteCallerChoosesTyForTyParam<'tcx> { pub ty_param_name: Symbol, pub found_ty: Ty<'tcx>, @@ -954,14 +1068,20 @@ pub(crate) struct NoteCallerChoosesTyForTyParam<'tcx> { #[derive(Subdiagnostic)] pub(crate) enum SuggestBoxingForReturnImplTrait { - #[multipart_suggestion(hir_typeck_rpit_change_return_type, applicability = "maybe-incorrect")] + #[multipart_suggestion( + "you could change the return type to be a boxed trait object", + applicability = "maybe-incorrect" + )] ChangeReturnType { #[suggestion_part(code = "Box, @@ -971,11 +1091,13 @@ pub(crate) enum SuggestBoxingForReturnImplTrait { } #[derive(Diagnostic)] -#[diag(hir_typeck_self_ctor_from_outer_item, code = E0401)] +#[diag("can't reference `Self` constructor from outer item", code = E0401)] pub(crate) struct SelfCtorFromOuterItem { #[primary_span] pub span: Span, - #[label] + #[label( + "the inner item doesn't inherit generics from this impl, so `Self` is invalid to reference" + )] pub impl_span: Span, #[subdiagnostic] pub sugg: Option, @@ -984,16 +1106,18 @@ pub(crate) struct SelfCtorFromOuterItem { } #[derive(Subdiagnostic)] -#[label(hir_typeck_self_ctor_from_outer_item_inner_item)] +#[label("`Self` used in this inner item")] pub(crate) struct InnerItem { #[primary_span] pub span: Span, } #[derive(LintDiagnostic)] -#[diag(hir_typeck_self_ctor_from_outer_item)] +#[diag("can't reference `Self` constructor from outer item")] pub(crate) struct SelfCtorFromOuterItemLint { - #[label] + #[label( + "the inner item doesn't inherit generics from this impl, so `Self` is invalid to reference" + )] pub impl_span: Span, #[subdiagnostic] pub sugg: Option, @@ -1002,7 +1126,11 @@ pub(crate) struct SelfCtorFromOuterItemLint { } #[derive(Subdiagnostic)] -#[suggestion(hir_typeck_suggestion, code = "{name}", applicability = "machine-applicable")] +#[suggestion( + "replace `Self` with the actual type", + code = "{name}", + applicability = "machine-applicable" +)] pub(crate) struct ReplaceWithName { #[primary_span] pub span: Span, @@ -1010,44 +1138,75 @@ pub(crate) struct ReplaceWithName { } #[derive(Diagnostic)] -#[diag(hir_typeck_cast_thin_pointer_to_wide_pointer, code = E0607)] +#[diag("cannot cast thin pointer `{$expr_ty}` to wide pointer `{$cast_ty}`", code = E0607)] pub(crate) struct CastThinPointerToWidePointer<'tcx> { #[primary_span] pub span: Span, pub expr_ty: Ty<'tcx>, pub cast_ty: Ty<'tcx>, - #[note(hir_typeck_teach_help)] + #[note( + "Thin pointers are \"simple\" pointers: they are purely a reference to a + memory address. + + Wide pointers are pointers referencing \"Dynamically Sized Types\" (also + called DST). DST don't have a statically known size, therefore they can + only exist behind some kind of pointers that contain additional + information. Slices and trait objects are DSTs. In the case of slices, + the additional information the wide pointer holds is their size. + + To fix this error, don't try to cast directly between thin and wide + pointers. + + For more information about casts, take a look at The Book: + https://doc.rust-lang.org/reference/expressions/operator-expr.html#type-cast-expressions" + )] pub(crate) teach: bool, } #[derive(Diagnostic)] -#[diag(hir_typeck_pass_to_variadic_function, code = E0617)] +#[diag("can't pass `{$ty}` to variadic function", code = E0617)] pub(crate) struct PassToVariadicFunction<'a, 'tcx> { #[primary_span] pub span: Span, pub ty: Ty<'tcx>, pub cast_ty: &'a str, - #[suggestion(code = " as {cast_ty}", applicability = "machine-applicable", style = "verbose")] + #[suggestion( + "cast the value to `{$cast_ty}`", + code = " as {cast_ty}", + applicability = "machine-applicable", + style = "verbose" + )] pub sugg_span: Span, - #[note(hir_typeck_teach_help)] + #[note( + "certain types, like `{$ty}`, must be cast before passing them to a variadic function to match the implicit cast that a C compiler would perform as part of C's numeric promotion rules" + )] pub(crate) teach: bool, } #[derive(Diagnostic)] -#[diag(hir_typeck_fn_item_to_variadic_function, code = E0617)] -#[help] -#[note] +#[diag("can't pass a function item to a variadic function", code = E0617)] +#[help( + "a function item is zero-sized and needs to be cast into a function pointer to be used in FFI" +)] +#[note( + "for more information on function items, visit https://doc.rust-lang.org/reference/types/function-item.html" +)] pub(crate) struct PassFnItemToVariadicFunction { #[primary_span] pub span: Span, - #[suggestion(code = " as {replace}", applicability = "machine-applicable", style = "verbose")] + #[suggestion( + "use a function pointer instead", + code = " as {replace}", + applicability = "machine-applicable", + style = "verbose" + )] pub sugg_span: Span, pub replace: String, } #[derive(Subdiagnostic)] #[suggestion( - hir_typeck_replace_comma_with_semicolon, + "replace the comma with a semicolon to create {$descr}", applicability = "machine-applicable", style = "verbose", code = "; " @@ -1059,7 +1218,7 @@ pub(crate) struct ReplaceCommaWithSemicolon { } #[derive(LintDiagnostic)] -#[diag(hir_typeck_supertrait_item_shadowing)] +#[diag("trait item `{$item}` from `{$subtrait}` shadows identically named item from supertrait")] pub(crate) struct SupertraitItemShadowing { pub item: Symbol, pub subtrait: Symbol, @@ -1070,7 +1229,7 @@ pub(crate) struct SupertraitItemShadowing { } #[derive(Subdiagnostic)] -#[note(hir_typeck_supertrait_item_shadower)] +#[note("item from `{$subtrait}` shadows a supertrait item")] pub(crate) struct SupertraitItemShadower { pub subtrait: Symbol, #[primary_span] @@ -1079,13 +1238,13 @@ pub(crate) struct SupertraitItemShadower { #[derive(Subdiagnostic)] pub(crate) enum SupertraitItemShadowee { - #[note(hir_typeck_supertrait_item_shadowee)] + #[note("item from `{$supertrait}` is shadowed by a subtrait item")] Labeled { #[primary_span] span: Span, supertrait: Symbol, }, - #[note(hir_typeck_supertrait_item_multiple_shadowee)] + #[note("items from several supertraits are shadowed: {$traits}")] Several { #[primary_span] spans: MultiSpan, @@ -1094,7 +1253,7 @@ pub(crate) enum SupertraitItemShadowee { } #[derive(Diagnostic)] -#[diag(hir_typeck_register_type_unstable)] +#[diag("type `{$ty}` cannot be used with this register class in stable")] pub(crate) struct RegisterTypeUnstable<'a> { #[primary_span] pub span: Span, @@ -1102,22 +1261,22 @@ pub(crate) struct RegisterTypeUnstable<'a> { } #[derive(Diagnostic)] -#[diag(hir_typeck_naked_asm_outside_naked_fn)] +#[diag("the `naked_asm!` macro can only be used in functions marked with `#[unsafe(naked)]`")] pub(crate) struct NakedAsmOutsideNakedFn { #[primary_span] pub span: Span, } #[derive(Diagnostic)] -#[diag(hir_typeck_no_patterns)] +#[diag("patterns not allowed in naked function parameters")] pub(crate) struct NoPatterns { #[primary_span] pub span: Span, } #[derive(Diagnostic)] -#[diag(hir_typeck_params_not_allowed)] -#[help] +#[diag("referencing function parameters is not allowed in naked functions")] +#[help("follow the calling convention in asm block to use parameters")] pub(crate) struct ParamsNotAllowed { #[primary_span] pub span: Span, @@ -1132,14 +1291,23 @@ pub(crate) struct NakedFunctionsAsmBlock { impl Diagnostic<'_, G> for NakedFunctionsAsmBlock { #[track_caller] fn into_diag(self, dcx: DiagCtxtHandle<'_>, level: Level) -> Diag<'_, G> { - let mut diag = Diag::new(dcx, level, fluent::hir_typeck_naked_functions_asm_block); + let mut diag = Diag::new( + dcx, + level, + inline_fluent!("naked functions must contain a single `naked_asm!` invocation"), + ); diag.span(self.span); diag.code(E0787); for span in self.multiple_asms.iter() { - diag.span_label(*span, fluent::hir_typeck_label_multiple_asm); + diag.span_label( + *span, + inline_fluent!( + "multiple `naked_asm!` invocations are not allowed in naked functions" + ), + ); } for span in self.non_asms.iter() { - diag.span_label(*span, fluent::hir_typeck_label_non_asm); + diag.span_label(*span, inline_fluent!("not allowed in naked functions")); } diag } @@ -1182,44 +1350,48 @@ pub(crate) fn maybe_emit_plus_equals_diagnostic<'a>( } #[derive(Diagnostic)] -#[diag(hir_typeck_naked_functions_must_naked_asm, code = E0787)] +#[diag("the `asm!` macro is not allowed in naked functions", code = E0787)] pub(crate) struct NakedFunctionsMustNakedAsm { #[primary_span] - #[label] + #[label("consider using the `naked_asm!` macro instead")] pub span: Span, } #[derive(Diagnostic)] -#[diag(hir_typeck_abi_cannot_be_called)] +#[diag("functions with the {$abi} ABI cannot be called")] pub(crate) struct AbiCannotBeCalled { #[primary_span] - #[note] + #[note("an `extern {$abi}` function can only be called using inline assembly")] pub span: Span, pub abi: ExternAbi, } #[derive(Diagnostic)] -#[diag(hir_typeck_gpu_kernel_abi_cannot_be_called)] +#[diag("functions with the \"gpu-kernel\" ABI cannot be called")] pub(crate) struct GpuKernelAbiCannotBeCalled { #[primary_span] - #[note] + #[note("an `extern \"gpu-kernel\"` function must be launched on the GPU by the runtime")] pub span: Span, } #[derive(Diagnostic)] -#[diag(hir_typeck_const_continue_bad_label)] +#[diag("`#[const_continue]` must break to a labeled block that participates in a `#[loop_match]`")] pub(crate) struct ConstContinueBadLabel { #[primary_span] pub span: Span, } #[derive(Diagnostic)] -#[diag(hir_typeck_project_on_non_pin_project_type)] +#[diag("cannot project on type that is not `#[pin_v2]`")] pub(crate) struct ProjectOnNonPinProjectType { #[primary_span] pub span: Span, - #[note] + #[note("type defined here")] pub def_span: Option, - #[suggestion(code = "#[pin_v2]\n", applicability = "machine-applicable")] + #[suggestion( + "add `#[pin_v2]` here", + code = "#[pin_v2]\n", + applicability = "machine-applicable" + )] pub sugg_span: Option, } diff --git a/compiler/rustc_hir_typeck/src/fn_ctxt/suggestions.rs b/compiler/rustc_hir_typeck/src/fn_ctxt/suggestions.rs index 3e4c194147f9f..934aa0a996143 100644 --- a/compiler/rustc_hir_typeck/src/fn_ctxt/suggestions.rs +++ b/compiler/rustc_hir_typeck/src/fn_ctxt/suggestions.rs @@ -5,7 +5,7 @@ use core::iter; use hir::def_id::LocalDefId; use rustc_ast::util::parser::ExprPrecedence; use rustc_data_structures::packed::Pu128; -use rustc_errors::{Applicability, Diag, MultiSpan, listify}; +use rustc_errors::{Applicability, Diag, MultiSpan, inline_fluent, listify}; use rustc_hir::def::{CtorKind, CtorOf, DefKind, Res}; use rustc_hir::lang_items::LangItem; use rustc_hir::{ @@ -33,10 +33,10 @@ use rustc_trait_selection::traits::query::evaluate_obligation::InferCtxtExt as _ use tracing::{debug, instrument}; use super::FnCtxt; +use crate::errors; use crate::fn_ctxt::rustc_span::BytePos; use crate::method::probe; use crate::method::probe::{IsSuggestion, Mode, ProbeScope}; -use crate::{errors, fluent_generated as fluent}; impl<'a, 'tcx> FnCtxt<'a, 'tcx> { pub(crate) fn body_fn_sig(&self) -> Option> { @@ -482,7 +482,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { let sugg = prefix_wrap(".map(|x| x.as_str())"); err.span_suggestion_verbose( expr.span.shrink_to_hi(), - fluent::hir_typeck_convert_to_str, + inline_fluent!("try converting the passed type into a `&str`"), sugg, Applicability::MachineApplicable, ); diff --git a/compiler/rustc_hir_typeck/src/lib.rs b/compiler/rustc_hir_typeck/src/lib.rs index 6e126b3013c99..ac3db41a4d665 100644 --- a/compiler/rustc_hir_typeck/src/lib.rs +++ b/compiler/rustc_hir_typeck/src/lib.rs @@ -67,8 +67,6 @@ use crate::expectation::Expectation; use crate::fn_ctxt::LoweredTy; use crate::gather_locals::GatherLocalsVisitor; -rustc_fluent_macro::fluent_messages! { "../messages.ftl" } - #[macro_export] macro_rules! type_error_struct { ($dcx:expr, $span:expr, $typ:expr, $code:expr, $($message:tt)*) => ({ diff --git a/compiler/rustc_incremental/Cargo.toml b/compiler/rustc_incremental/Cargo.toml index ae96cc62e54a3..ac4d7d8e1cbc0 100644 --- a/compiler/rustc_incremental/Cargo.toml +++ b/compiler/rustc_incremental/Cargo.toml @@ -6,7 +6,6 @@ edition = "2024" [dependencies] # tidy-alphabetical-start rand = "0.9.0" -rustc_ast = { path = "../rustc_ast" } rustc_data_structures = { path = "../rustc_data_structures" } rustc_errors = { path = "../rustc_errors" } rustc_fs_util = { path = "../rustc_fs_util" } @@ -18,6 +17,5 @@ rustc_middle = { path = "../rustc_middle" } rustc_serialize = { path = "../rustc_serialize" } rustc_session = { path = "../rustc_session" } rustc_span = { path = "../rustc_span" } -thin-vec = "0.2.12" tracing = "0.1" # tidy-alphabetical-end diff --git a/compiler/rustc_incremental/src/assert_dep_graph.rs b/compiler/rustc_incremental/src/assert_dep_graph.rs index 0e04a2a784ec8..3447836598bf0 100644 --- a/compiler/rustc_incremental/src/assert_dep_graph.rs +++ b/compiler/rustc_incremental/src/assert_dep_graph.rs @@ -5,7 +5,7 @@ //! annotations. These annotations can be used to test whether paths //! exist in the graph. These checks run after codegen, so they view the //! the final state of the dependency graph. Note that there are -//! similar assertions found in `persist::dirty_clean` which check the +//! similar assertions found in `persist::clean` which check the //! **initial** state of the dependency graph, just after it has been //! loaded from disk. //! @@ -39,14 +39,16 @@ use std::io::Write; use rustc_data_structures::fx::FxIndexSet; use rustc_data_structures::graph::linked_graph::{Direction, INCOMING, NodeIndex, OUTGOING}; +use rustc_hir::Attribute; +use rustc_hir::attrs::AttributeKind; use rustc_hir::def_id::{CRATE_DEF_ID, DefId, LocalDefId}; use rustc_hir::intravisit::{self, Visitor}; +use rustc_middle::bug; use rustc_middle::dep_graph::{ DepGraphQuery, DepKind, DepNode, DepNodeExt, DepNodeFilter, EdgeFilter, dep_kinds, }; use rustc_middle::hir::nested_filter; use rustc_middle::ty::TyCtxt; -use rustc_middle::{bug, span_bug}; use rustc_span::{Span, Symbol, sym}; use tracing::debug; use {rustc_graphviz as dot, rustc_hir as hir}; @@ -105,29 +107,13 @@ struct IfThisChanged<'tcx> { } impl<'tcx> IfThisChanged<'tcx> { - fn argument(&self, attr: &hir::Attribute) -> Option { - let mut value = None; - for list_item in attr.meta_item_list().unwrap_or_default() { - match list_item.ident() { - Some(ident) if list_item.is_word() && value.is_none() => value = Some(ident.name), - _ => - // FIXME better-encapsulate meta_item (don't directly access `node`) - { - span_bug!(list_item.span(), "unexpected meta-item {:?}", list_item) - } - } - } - value - } - fn process_attrs(&mut self, def_id: LocalDefId) { let def_path_hash = self.tcx.def_path_hash(def_id.to_def_id()); let hir_id = self.tcx.local_def_id_to_hir_id(def_id); let attrs = self.tcx.hir_attrs(hir_id); for attr in attrs { - if attr.has_name(sym::rustc_if_this_changed) { - let dep_node_interned = self.argument(attr); - let dep_node = match dep_node_interned { + if let Attribute::Parsed(AttributeKind::RustcIfThisChanged(span, dep_node)) = *attr { + let dep_node = match dep_node { None => DepNode::from_def_path_hash( self.tcx, def_path_hash, @@ -136,36 +122,29 @@ impl<'tcx> IfThisChanged<'tcx> { Some(n) => { match DepNode::from_label_string(self.tcx, n.as_str(), def_path_hash) { Ok(n) => n, - Err(()) => self.tcx.dcx().emit_fatal(errors::UnrecognizedDepNode { - span: attr.span(), - name: n, - }), + Err(()) => self + .tcx + .dcx() + .emit_fatal(errors::UnrecognizedDepNode { span, name: n }), } } }; - self.if_this_changed.push((attr.span(), def_id.to_def_id(), dep_node)); - } else if attr.has_name(sym::rustc_then_this_would_need) { - let dep_node_interned = self.argument(attr); - let dep_node = match dep_node_interned { - Some(n) => { - match DepNode::from_label_string(self.tcx, n.as_str(), def_path_hash) { - Ok(n) => n, - Err(()) => self.tcx.dcx().emit_fatal(errors::UnrecognizedDepNode { - span: attr.span(), - name: n, - }), - } - } - None => { - self.tcx.dcx().emit_fatal(errors::MissingDepNode { span: attr.span() }); - } - }; - self.then_this_would_need.push(( - attr.span(), - dep_node_interned.unwrap(), - hir_id, - dep_node, - )); + self.if_this_changed.push((span, def_id.to_def_id(), dep_node)); + } else if let Attribute::Parsed(AttributeKind::RustcThenThisWouldNeed( + _, + ref dep_nodes, + )) = *attr + { + for &n in dep_nodes { + let Ok(dep_node) = + DepNode::from_label_string(self.tcx, n.as_str(), def_path_hash) + else { + self.tcx + .dcx() + .emit_fatal(errors::UnrecognizedDepNode { span: n.span, name: n.name }); + }; + self.then_this_would_need.push((n.span, n.name, hir_id, dep_node)); + } } } } diff --git a/compiler/rustc_incremental/src/errors.rs b/compiler/rustc_incremental/src/errors.rs index 65109fdec03a7..9b33b49d4406a 100644 --- a/compiler/rustc_incremental/src/errors.rs +++ b/compiler/rustc_incremental/src/errors.rs @@ -1,7 +1,7 @@ use std::path::{Path, PathBuf}; use rustc_macros::Diagnostic; -use rustc_span::{Ident, Span, Symbol}; +use rustc_span::{Span, Symbol}; #[derive(Diagnostic)] #[diag("unrecognized `DepNode` variant: {$name}")] @@ -11,13 +11,6 @@ pub(crate) struct UnrecognizedDepNode { pub name: Symbol, } -#[derive(Diagnostic)] -#[diag("missing `DepNode` variant")] -pub(crate) struct MissingDepNode { - #[primary_span] - pub span: Span, -} - #[derive(Diagnostic)] #[diag("no `#[rustc_if_this_changed]` annotation detected")] pub(crate) struct MissingIfThisChanged { @@ -106,42 +99,12 @@ pub(crate) struct NotLoaded<'a> { pub dep_node_str: &'a str, } -#[derive(Diagnostic)] -#[diag("unknown `rustc_clean` argument")] -pub(crate) struct UnknownRustcCleanArgument { - #[primary_span] - pub span: Span, -} - -#[derive(Diagnostic)] -#[diag("no cfg attribute")] -pub(crate) struct NoCfg { - #[primary_span] - pub span: Span, -} - -#[derive(Diagnostic)] -#[diag("associated value expected for `{$ident}`")] -pub(crate) struct AssociatedValueExpectedFor { - #[primary_span] - pub span: Span, - pub ident: Ident, -} - -#[derive(Diagnostic)] -#[diag("expected an associated value")] -pub(crate) struct AssociatedValueExpected { - #[primary_span] - pub span: Span, -} - #[derive(Diagnostic)] #[diag("found unchecked `#[rustc_clean]` attribute")] pub(crate) struct UncheckedClean { #[primary_span] pub span: Span, } - #[derive(Diagnostic)] #[diag("unable to delete old {$name} at `{$path}`: {$err}")] pub(crate) struct DeleteOld<'a> { diff --git a/compiler/rustc_incremental/src/persist/dirty_clean.rs b/compiler/rustc_incremental/src/persist/clean.rs similarity index 73% rename from compiler/rustc_incremental/src/persist/dirty_clean.rs rename to compiler/rustc_incremental/src/persist/clean.rs index 71fb188952466..d83ba5a78bed5 100644 --- a/compiler/rustc_incremental/src/persist/dirty_clean.rs +++ b/compiler/rustc_incremental/src/persist/clean.rs @@ -19,26 +19,22 @@ //! Errors are reported if we are in the suitable configuration but //! the required condition is not met. -use rustc_ast::{self as ast, MetaItemInner}; use rustc_data_structures::fx::FxHashSet; use rustc_data_structures::unord::UnordSet; +use rustc_hir::attrs::{AttributeKind, RustcCleanAttribute}; use rustc_hir::def_id::LocalDefId; use rustc_hir::{ - Attribute, ImplItemKind, ItemKind as HirItem, Node as HirNode, TraitItemKind, intravisit, + Attribute, ImplItemKind, ItemKind as HirItem, Node as HirNode, TraitItemKind, find_attr, + intravisit, }; use rustc_middle::dep_graph::{DepNode, DepNodeExt, dep_kind_from_label, label_strs}; use rustc_middle::hir::nested_filter; use rustc_middle::ty::TyCtxt; -use rustc_span::{Span, Symbol, sym}; -use thin_vec::ThinVec; +use rustc_span::{Span, Symbol}; use tracing::debug; use crate::errors; -const LOADED_FROM_DISK: Symbol = sym::loaded_from_disk; -const EXCEPT: Symbol = sym::except; -const CFG: Symbol = sym::cfg; - // Base and Extra labels to build up the labels /// For typedef, constants, and statics @@ -127,14 +123,14 @@ const LABELS_ADT: &[&[&str]] = &[BASE_HIR, BASE_STRUCT]; type Labels = UnordSet; -/// Represents the requested configuration by rustc_clean/dirty +/// Represents the requested configuration by rustc_clean struct Assertion { clean: Labels, dirty: Labels, loaded_from_disk: Labels, } -pub(crate) fn check_dirty_clean_annotations(tcx: TyCtxt<'_>) { +pub(crate) fn check_clean_annotations(tcx: TyCtxt<'_>) { if !tcx.sess.opts.unstable_opts.query_dep_graph { return; } @@ -145,24 +141,24 @@ pub(crate) fn check_dirty_clean_annotations(tcx: TyCtxt<'_>) { } tcx.dep_graph.with_ignore(|| { - let mut dirty_clean_visitor = DirtyCleanVisitor { tcx, checked_attrs: Default::default() }; + let mut clean_visitor = CleanVisitor { tcx, checked_attrs: Default::default() }; let crate_items = tcx.hir_crate_items(()); for id in crate_items.free_items() { - dirty_clean_visitor.check_item(id.owner_id.def_id); + clean_visitor.check_item(id.owner_id.def_id); } for id in crate_items.trait_items() { - dirty_clean_visitor.check_item(id.owner_id.def_id); + clean_visitor.check_item(id.owner_id.def_id); } for id in crate_items.impl_items() { - dirty_clean_visitor.check_item(id.owner_id.def_id); + clean_visitor.check_item(id.owner_id.def_id); } for id in crate_items.foreign_items() { - dirty_clean_visitor.check_item(id.owner_id.def_id); + clean_visitor.check_item(id.owner_id.def_id); } let mut all_attrs = FindAllAttrs { tcx, found_attrs: vec![] }; @@ -171,67 +167,62 @@ pub(crate) fn check_dirty_clean_annotations(tcx: TyCtxt<'_>) { // Note that we cannot use the existing "unused attribute"-infrastructure // here, since that is running before codegen. This is also the reason why // all codegen-specific attributes are `AssumedUsed` in rustc_ast::feature_gate. - all_attrs.report_unchecked_attrs(dirty_clean_visitor.checked_attrs); + all_attrs.report_unchecked_attrs(clean_visitor.checked_attrs); }) } -struct DirtyCleanVisitor<'tcx> { +struct CleanVisitor<'tcx> { tcx: TyCtxt<'tcx>, - checked_attrs: FxHashSet, + checked_attrs: FxHashSet, } -impl<'tcx> DirtyCleanVisitor<'tcx> { - /// Possibly "deserialize" the attribute into a clean/dirty assertion - fn assertion_maybe(&mut self, item_id: LocalDefId, attr: &Attribute) -> Option { - assert!(attr.has_name(sym::rustc_clean)); - if !check_config(self.tcx, attr) { - // skip: not the correct `cfg=` - return None; - } - let assertion = self.assertion_auto(item_id, attr); - Some(assertion) +impl<'tcx> CleanVisitor<'tcx> { + /// Convert the attribute to an [`Assertion`] if the relevant cfg is active + fn assertion_maybe( + &mut self, + item_id: LocalDefId, + attr: &RustcCleanAttribute, + ) -> Option { + self.tcx + .sess + .psess + .config + .contains(&(attr.cfg, None)) + .then(|| self.assertion_auto(item_id, attr)) } /// Gets the "auto" assertion on pre-validated attr, along with the `except` labels. - fn assertion_auto(&mut self, item_id: LocalDefId, attr: &Attribute) -> Assertion { - let (name, mut auto) = self.auto_labels(item_id, attr); + fn assertion_auto(&mut self, item_id: LocalDefId, attr: &RustcCleanAttribute) -> Assertion { + let (name, mut auto) = self.auto_labels(item_id, attr.span); let except = self.except(attr); let loaded_from_disk = self.loaded_from_disk(attr); for e in except.items().into_sorted_stable_ord() { if !auto.remove(e) { - self.tcx.dcx().emit_fatal(errors::AssertionAuto { span: attr.span(), name, e }); + self.tcx.dcx().emit_fatal(errors::AssertionAuto { span: attr.span, name, e }); } } Assertion { clean: auto, dirty: except, loaded_from_disk } } /// `loaded_from_disk=` attribute value - fn loaded_from_disk(&self, attr: &Attribute) -> Labels { - for item in attr.meta_item_list().unwrap_or_else(ThinVec::new) { - if item.has_name(LOADED_FROM_DISK) { - let value = expect_associated_value(self.tcx, &item); - return self.resolve_labels(&item, value); - } - } - // If `loaded_from_disk=` is not specified, don't assert anything - Labels::default() + fn loaded_from_disk(&self, attr: &RustcCleanAttribute) -> Labels { + attr.loaded_from_disk + .as_ref() + .map(|queries| self.resolve_labels(&queries.entries, queries.span)) + .unwrap_or_default() } /// `except=` attribute value - fn except(&self, attr: &Attribute) -> Labels { - for item in attr.meta_item_list().unwrap_or_else(ThinVec::new) { - if item.has_name(EXCEPT) { - let value = expect_associated_value(self.tcx, &item); - return self.resolve_labels(&item, value); - } - } - // if no `label` or `except` is given, only the node's group are asserted - Labels::default() + fn except(&self, attr: &RustcCleanAttribute) -> Labels { + attr.except + .as_ref() + .map(|queries| self.resolve_labels(&queries.entries, queries.span)) + .unwrap_or_default() } /// Return all DepNode labels that should be asserted for this item. /// index=0 is the "name" used for error messages - fn auto_labels(&mut self, item_id: LocalDefId, attr: &Attribute) -> (&'static str, Labels) { + fn auto_labels(&mut self, item_id: LocalDefId, span: Span) -> (&'static str, Labels) { let node = self.tcx.hir_node_by_def_id(item_id); let (name, labels) = match node { HirNode::Item(item) => { @@ -282,7 +273,7 @@ impl<'tcx> DirtyCleanVisitor<'tcx> { HirItem::Impl { .. } => ("ItemKind::Impl", LABELS_IMPL), _ => self.tcx.dcx().emit_fatal(errors::UndefinedCleanDirtyItem { - span: attr.span(), + span, kind: format!("{:?}", item.kind), }), } @@ -297,31 +288,31 @@ impl<'tcx> DirtyCleanVisitor<'tcx> { ImplItemKind::Const(..) => ("NodeImplConst", LABELS_CONST_IN_IMPL), ImplItemKind::Type(..) => ("NodeImplType", LABELS_CONST_IN_IMPL), }, - _ => self.tcx.dcx().emit_fatal(errors::UndefinedCleanDirty { - span: attr.span(), - kind: format!("{node:?}"), - }), + _ => self + .tcx + .dcx() + .emit_fatal(errors::UndefinedCleanDirty { span, kind: format!("{node:?}") }), }; let labels = Labels::from_iter(labels.iter().flat_map(|s| s.iter().map(|l| (*l).to_string()))); (name, labels) } - fn resolve_labels(&self, item: &MetaItemInner, value: Symbol) -> Labels { + fn resolve_labels(&self, values: &[Symbol], span: Span) -> Labels { let mut out = Labels::default(); - for label in value.as_str().split(',') { - let label = label.trim(); - if DepNode::has_label_string(label) { - if out.contains(label) { + for label in values { + let label_str = label.as_str(); + if DepNode::has_label_string(label_str) { + if out.contains(label_str) { self.tcx .dcx() - .emit_fatal(errors::RepeatedDepNodeLabel { span: item.span(), label }); + .emit_fatal(errors::RepeatedDepNodeLabel { span, label: label_str }); } - out.insert(label.to_string()); + out.insert(label_str.to_string()); } else { self.tcx .dcx() - .emit_fatal(errors::UnrecognizedDepNodeLabel { span: item.span(), label }); + .emit_fatal(errors::UnrecognizedDepNodeLabel { span, label: label_str }); } } out @@ -360,11 +351,18 @@ impl<'tcx> DirtyCleanVisitor<'tcx> { fn check_item(&mut self, item_id: LocalDefId) { let item_span = self.tcx.def_span(item_id.to_def_id()); let def_path_hash = self.tcx.def_path_hash(item_id.to_def_id()); - for attr in self.tcx.get_attrs(item_id, sym::rustc_clean) { + + let Some(attr) = + find_attr!(self.tcx.get_all_attrs(item_id), AttributeKind::RustcClean(attr) => attr) + else { + return; + }; + + for attr in attr { let Some(assertion) = self.assertion_maybe(item_id, attr) else { continue; }; - self.checked_attrs.insert(attr.id()); + self.checked_attrs.insert(attr.span); for label in assertion.clean.items().into_sorted_stable_ord() { let dep_node = DepNode::from_label_string(self.tcx, label, def_path_hash).unwrap(); self.assert_clean(item_span, dep_node); @@ -400,61 +398,24 @@ impl<'tcx> DirtyCleanVisitor<'tcx> { } } -/// Given a `#[rustc_clean]` attribute, scan for a `cfg="foo"` attribute and check whether we have -/// a cfg flag called `foo`. -fn check_config(tcx: TyCtxt<'_>, attr: &Attribute) -> bool { - debug!("check_config(attr={:?})", attr); - let config = &tcx.sess.psess.config; - debug!("check_config: config={:?}", config); - let mut cfg = None; - for item in attr.meta_item_list().unwrap_or_else(ThinVec::new) { - if item.has_name(CFG) { - let value = expect_associated_value(tcx, &item); - debug!("check_config: searching for cfg {:?}", value); - cfg = Some(config.contains(&(value, None))); - } else if !(item.has_name(EXCEPT) || item.has_name(LOADED_FROM_DISK)) { - tcx.dcx().emit_err(errors::UnknownRustcCleanArgument { span: item.span() }); - } - } - - match cfg { - None => tcx.dcx().emit_fatal(errors::NoCfg { span: attr.span() }), - Some(c) => c, - } -} - -fn expect_associated_value(tcx: TyCtxt<'_>, item: &MetaItemInner) -> Symbol { - if let Some(value) = item.value_str() { - value - } else if let Some(ident) = item.ident() { - tcx.dcx().emit_fatal(errors::AssociatedValueExpectedFor { span: item.span(), ident }); - } else { - tcx.dcx().emit_fatal(errors::AssociatedValueExpected { span: item.span() }); - } -} - /// A visitor that collects all `#[rustc_clean]` attributes from /// the HIR. It is used to verify that we really ran checks for all annotated /// nodes. struct FindAllAttrs<'tcx> { tcx: TyCtxt<'tcx>, - found_attrs: Vec<&'tcx Attribute>, + found_attrs: Vec<&'tcx RustcCleanAttribute>, } impl<'tcx> FindAllAttrs<'tcx> { - fn is_active_attr(&mut self, attr: &Attribute) -> bool { - if attr.has_name(sym::rustc_clean) && check_config(self.tcx, attr) { - return true; - } - - false + fn is_active_attr(&self, attr: &RustcCleanAttribute) -> bool { + self.tcx.sess.psess.config.contains(&(attr.cfg, None)) } - fn report_unchecked_attrs(&self, mut checked_attrs: FxHashSet) { + fn report_unchecked_attrs(&self, mut checked_attrs: FxHashSet) { for attr in &self.found_attrs { - if !checked_attrs.contains(&attr.id()) { - self.tcx.dcx().emit_err(errors::UncheckedClean { span: attr.span() }); - checked_attrs.insert(attr.id()); + if !checked_attrs.contains(&attr.span) { + self.tcx.dcx().emit_err(errors::UncheckedClean { span: attr.span }); + checked_attrs.insert(attr.span); } } } @@ -468,8 +429,12 @@ impl<'tcx> intravisit::Visitor<'tcx> for FindAllAttrs<'tcx> { } fn visit_attribute(&mut self, attr: &'tcx Attribute) { - if self.is_active_attr(attr) { - self.found_attrs.push(attr); + if let Attribute::Parsed(AttributeKind::RustcClean(attrs)) = attr { + for attr in attrs { + if self.is_active_attr(attr) { + self.found_attrs.push(attr); + } + } } } } diff --git a/compiler/rustc_incremental/src/persist/mod.rs b/compiler/rustc_incremental/src/persist/mod.rs index f5d5167e0e2cd..a3857967ab081 100644 --- a/compiler/rustc_incremental/src/persist/mod.rs +++ b/compiler/rustc_incremental/src/persist/mod.rs @@ -2,8 +2,8 @@ //! into the given directory. At the same time, it also hashes the //! various HIR nodes. +mod clean; mod data; -mod dirty_clean; mod file_format; mod fs; mod load; diff --git a/compiler/rustc_incremental/src/persist/save.rs b/compiler/rustc_incremental/src/persist/save.rs index 58fea3278a839..be16b543e824d 100644 --- a/compiler/rustc_incremental/src/persist/save.rs +++ b/compiler/rustc_incremental/src/persist/save.rs @@ -14,7 +14,7 @@ use tracing::debug; use super::data::*; use super::fs::*; -use super::{dirty_clean, file_format, work_product}; +use super::{clean, file_format, work_product}; use crate::assert_dep_graph::assert_dep_graph; use crate::errors; @@ -42,7 +42,7 @@ pub(crate) fn save_dep_graph(tcx: TyCtxt<'_>) { let staging_dep_graph_path = staging_dep_graph_path(sess); sess.time("assert_dep_graph", || assert_dep_graph(tcx)); - sess.time("check_dirty_clean", || dirty_clean::check_dirty_clean_annotations(tcx)); + sess.time("check_clean", || clean::check_clean_annotations(tcx)); join( move || { diff --git a/compiler/rustc_metadata/Cargo.toml b/compiler/rustc_metadata/Cargo.toml index 1b40d9f684efc..3a70ee130c27b 100644 --- a/compiler/rustc_metadata/Cargo.toml +++ b/compiler/rustc_metadata/Cargo.toml @@ -15,7 +15,6 @@ rustc_data_structures = { path = "../rustc_data_structures" } rustc_errors = { path = "../rustc_errors" } rustc_expand = { path = "../rustc_expand" } rustc_feature = { path = "../rustc_feature" } -rustc_fluent_macro = { path = "../rustc_fluent_macro" } rustc_fs_util = { path = "../rustc_fs_util" } rustc_hir = { path = "../rustc_hir" } rustc_hir_pretty = { path = "../rustc_hir_pretty" } diff --git a/compiler/rustc_metadata/messages.ftl b/compiler/rustc_metadata/messages.ftl deleted file mode 100644 index fac7b6c21f60c..0000000000000 --- a/compiler/rustc_metadata/messages.ftl +++ /dev/null @@ -1,240 +0,0 @@ -metadata_async_drop_types_in_dependency = - found async drop types in dependency `{$extern_crate}`, but async_drop feature is disabled for `{$local_crate}` - .help = if async drop type will be dropped in a crate without `feature(async_drop)`, sync Drop will be used - -metadata_bad_panic_strategy = - the linked panic runtime `{$runtime}` is not compiled with this crate's panic strategy `{$strategy}` - -metadata_binary_output_to_tty = - option `-o` or `--emit` is used to write binary output type `metadata` to stdout, but stdout is a tty - -metadata_cannot_find_crate = - can't find crate for `{$crate_name}`{$add_info} - -metadata_cant_find_crate = - can't find crate - -metadata_compiler_missing_profiler = - the compiler may have been built without the profiler runtime - -metadata_conflicting_alloc_error_handler = - the `#[alloc_error_handler]` in {$other_crate_name} conflicts with allocation error handler in: {$crate_name} - -metadata_conflicting_global_alloc = - the `#[global_allocator]` in {$other_crate_name} conflicts with global allocator in: {$crate_name} - -metadata_consider_adding_std = - consider adding the standard library to the sysroot with `x build library --target {$locator_triple}` - -metadata_consider_building_std = - consider building the standard library from source with `cargo build -Zbuild-std` - -metadata_consider_downloading_target = - consider downloading the target with `rustup target add {$locator_triple}` - -metadata_crate_dep_multiple = - cannot satisfy dependencies so `{$crate_name}` only shows up once - .help = having upstream crates all available in one format will likely make this go away - -metadata_crate_dep_not_static = - `{$crate_name}` was unavailable as a static crate, preventing fully static linking - -metadata_crate_dep_rustc_driver = - `feature(rustc_private)` is needed to link to the compiler's `rustc_driver` library - -metadata_crate_location_unknown_type = - extern location for {$crate_name} is of an unknown type: {$path} - -metadata_crate_not_compiler_builtins = - the crate `{$crate_name}` resolved as `compiler_builtins` but is not `#![compiler_builtins]` - -metadata_crate_not_panic_runtime = - the crate `{$crate_name}` is not a panic runtime - -metadata_dl_error = - {$path}{$err} - -metadata_empty_renaming_target = - an empty renaming target was specified for library `{$lib_name}` - -metadata_extern_location_not_exist = - extern location for {$crate_name} does not exist: {$location} - -metadata_extern_location_not_file = - extern location for {$crate_name} is not a file: {$location} - -metadata_fail_create_file_encoder = - failed to create file encoder: {$err} - -metadata_fail_write_file = - failed to write to `{$path}`: {$err} - -metadata_failed_copy_to_stdout = - failed to copy {$filename} to stdout: {$err} - -metadata_failed_create_encoded_metadata = - failed to create encoded metadata from file: {$err} - -metadata_failed_create_file = - failed to create the file {$filename}: {$err} - -metadata_failed_create_tempdir = - couldn't create a temp dir: {$err} - -metadata_failed_write_error = - failed to write {$filename}: {$err} - -metadata_found_crate_versions = - the following crate versions were found:{$found_crates} - -metadata_found_staticlib = - found staticlib `{$crate_name}` instead of rlib or dylib{$add_info} - .help = please recompile that crate using --crate-type lib - -metadata_full_metadata_not_found = - only metadata stub found for `{$flavor}` dependency `{$crate_name}` - please provide path to the corresponding .rmeta file with full metadata - -metadata_global_alloc_required = - no global memory allocator found but one is required; link to std or add `#[global_allocator]` to a static item that implements the GlobalAlloc trait - -metadata_incompatible_panic_in_drop_strategy = - the crate `{$crate_name}` is compiled with the panic-in-drop strategy `{$found_strategy}` which is incompatible with this crate's strategy of `{$desired_strategy}` - -metadata_incompatible_rustc = - found crate `{$crate_name}` compiled by an incompatible version of rustc{$add_info} - .help = please recompile that crate using this compiler ({$rustc_version}) (consider running `cargo clean` first) - -metadata_incompatible_target_modifiers = - mixing `{$flag_name_prefixed}` will cause an ABI mismatch in crate `{$local_crate}` - .note = `{$flag_name_prefixed}={$local_value}` in this crate is incompatible with `{$flag_name_prefixed}={$extern_value}` in dependency `{$extern_crate}` - .help = the `{$flag_name_prefixed}` flag modifies the ABI so Rust crates compiled with different values of this flag cannot be used together safely -metadata_incompatible_target_modifiers_help_allow = if you are sure this will not cause problems, you may use `-Cunsafe-allow-abi-mismatch={$flag_name}` to silence this error -metadata_incompatible_target_modifiers_help_fix = set `{$flag_name_prefixed}={$extern_value}` in this crate or `{$flag_name_prefixed}={$local_value}` in `{$extern_crate}` - -metadata_incompatible_target_modifiers_help_fix_l_missed = set `{$flag_name_prefixed}={$extern_value}` in this crate or unset `{$flag_name_prefixed}` in `{$extern_crate}` - -metadata_incompatible_target_modifiers_help_fix_r_missed = unset `{$flag_name_prefixed}` in this crate or set `{$flag_name_prefixed}={$local_value}` in `{$extern_crate}` - -metadata_incompatible_target_modifiers_l_missed = - mixing `{$flag_name_prefixed}` will cause an ABI mismatch in crate `{$local_crate}` - .note = unset `{$flag_name_prefixed}` in this crate is incompatible with `{$flag_name_prefixed}={$extern_value}` in dependency `{$extern_crate}` - .help = the `{$flag_name_prefixed}` flag modifies the ABI so Rust crates compiled with different values of this flag cannot be used together safely -metadata_incompatible_target_modifiers_r_missed = - mixing `{$flag_name_prefixed}` will cause an ABI mismatch in crate `{$local_crate}` - .note = `{$flag_name_prefixed}={$local_value}` in this crate is incompatible with unset `{$flag_name_prefixed}` in dependency `{$extern_crate}` - .help = the `{$flag_name_prefixed}` flag modifies the ABI so Rust crates compiled with different values of this flag cannot be used together safely - -metadata_incompatible_with_immediate_abort = - the crate `{$crate_name}` was compiled with a panic strategy which is incompatible with `immediate-abort` - -metadata_incompatible_with_immediate_abort_core = - the crate `core` was compiled with a panic strategy which is incompatible with `immediate-abort` - .help = consider building the standard library from source with `cargo build -Zbuild-std` - -metadata_install_missing_components = - maybe you need to install the missing components with: `rustup component add rust-src rustc-dev llvm-tools-preview` - -metadata_invalid_meta_files = - found invalid metadata files for crate `{$crate_name}`{$add_info} - -metadata_lib_filename_form = - file name should be lib*.rlib or {$dll_prefix}*{$dll_suffix} - -metadata_lib_framework_apple = - library kind `framework` is only supported on Apple targets - -metadata_lib_required = - crate `{$crate_name}` required to be available in {$kind} format, but was not found in this form - -metadata_link_ordinal_raw_dylib = - `#[link_ordinal]` is only supported if link kind is `raw-dylib` - -metadata_missing_native_library = - could not find native static library `{$libname}`, perhaps an -L flag is missing? - -metadata_multiple_candidates = - multiple candidates for `{$flavor}` dependency `{$crate_name}` found - -metadata_multiple_renamings = - multiple renamings were specified for library `{$lib_name}` - -metadata_newer_crate_version = - found possibly newer version of crate `{$crate_name}`{$add_info} - .note = perhaps that crate needs to be recompiled? - -metadata_no_crate_with_triple = - couldn't find crate `{$crate_name}` with expected target triple {$locator_triple}{$add_info} - -metadata_no_link_mod_override = - overriding linking modifiers from command line is not supported - -metadata_no_multiple_alloc_error_handler = - cannot define multiple allocation error handlers - .label = cannot define a new allocation error handler - -metadata_no_multiple_global_alloc = - cannot define multiple global allocators - .label = cannot define a new global allocator - -metadata_no_panic_strategy = - the crate `{$crate_name}` does not have the panic strategy `{$strategy}` - -metadata_no_transitive_needs_dep = - the crate `{$crate_name}` cannot depend on a crate that needs {$needs_crate_name}, but it depends on `{$deps_crate_name}` - -metadata_non_ascii_name = - cannot load a crate with a non-ascii name `{$crate_name}` - -metadata_not_profiler_runtime = - the crate `{$crate_name}` is not a profiler runtime - -metadata_only_provide_library_name = only provide the library name `{$suggested_name}`, not the full filename - -metadata_prev_alloc_error_handler = - previous allocation error handler defined here - -metadata_prev_global_alloc = - previous global allocator defined here - -metadata_raw_dylib_malformed = - link name must be well-formed if link kind is `raw-dylib` -metadata_raw_dylib_unsupported_abi = - ABI not supported by `#[link(kind = "raw-dylib")]` on this architecture - -metadata_renaming_no_link = - renaming of the library `{$lib_name}` was specified, however this crate contains no `#[link(...)]` attributes referencing this library - -metadata_required_panic_strategy = - the crate `{$crate_name}` requires panic strategy `{$found_strategy}` which is incompatible with this crate's strategy of `{$desired_strategy}` - -metadata_rlib_required = - crate `{$crate_name}` required to be available in rlib format, but was not found in this form - -metadata_rustc_lib_required = - crate `{$crate_name}` required to be available in {$kind} format, but was not found in this form - .note = only .rmeta files are distributed for `rustc_private` crates other than `rustc_driver` - .help = try adding `extern crate rustc_driver;` at the top level of this crate - -metadata_stable_crate_id_collision = - found crates (`{$crate_name0}` and `{$crate_name1}`) with colliding StableCrateId values - -metadata_std_required = - `std` is required by `{$current_crate}` because it does not declare `#![no_std]` - -metadata_symbol_conflicts_current = - the current crate is indistinguishable from one of its dependencies: it has the same crate-name `{$crate_name}` and was compiled with the same `-C metadata` arguments, so this will result in symbol conflicts between the two - -metadata_target_no_std_support = - the `{$locator_triple}` target may not support the standard library - -metadata_target_not_installed = - the `{$locator_triple}` target may not be installed - -metadata_two_panic_runtimes = - cannot link together two panic runtimes: {$prev_name} and {$cur_name} - -metadata_unknown_target_modifier_unsafe_allowed = unknown target modifier `{$flag_name}`, requested by `-Cunsafe-allow-abi-mismatch={$flag_name}` - -metadata_wasm_c_abi = - older versions of the `wasm-bindgen` crate are incompatible with current versions of Rust; please update to `wasm-bindgen` v0.2.88 diff --git a/compiler/rustc_metadata/src/errors.rs b/compiler/rustc_metadata/src/errors.rs index 8eb4fad078fe8..da26f855b6c79 100644 --- a/compiler/rustc_metadata/src/errors.rs +++ b/compiler/rustc_metadata/src/errors.rs @@ -2,38 +2,43 @@ use std::io::Error; use std::path::{Path, PathBuf}; use rustc_errors::codes::*; -use rustc_errors::{Diag, DiagCtxtHandle, Diagnostic, EmissionGuarantee, Level}; +use rustc_errors::{Diag, DiagCtxtHandle, Diagnostic, EmissionGuarantee, Level, inline_fluent}; use rustc_macros::{Diagnostic, Subdiagnostic}; use rustc_span::{Span, Symbol, sym}; use rustc_target::spec::{PanicStrategy, TargetTuple}; -use crate::fluent_generated as fluent; use crate::locator::CrateFlavor; #[derive(Diagnostic)] -#[diag(metadata_rlib_required)] +#[diag( + "crate `{$crate_name}` required to be available in rlib format, but was not found in this form" +)] pub struct RlibRequired { pub crate_name: Symbol, } #[derive(Diagnostic)] -#[diag(metadata_lib_required)] +#[diag( + "crate `{$crate_name}` required to be available in {$kind} format, but was not found in this form" +)] pub struct LibRequired<'a> { pub crate_name: Symbol, pub kind: &'a str, } #[derive(Diagnostic)] -#[diag(metadata_rustc_lib_required)] -#[help] +#[diag( + "crate `{$crate_name}` required to be available in {$kind} format, but was not found in this form" +)] +#[help("try adding `extern crate rustc_driver;` at the top level of this crate")] pub struct RustcLibRequired<'a> { pub crate_name: Symbol, pub kind: &'a str, } #[derive(Diagnostic)] -#[diag(metadata_crate_dep_multiple)] -#[help] +#[diag("cannot satisfy dependencies so `{$crate_name}` only shows up once")] +#[help("having upstream crates all available in one format will likely make this go away")] pub struct CrateDepMultiple { pub crate_name: Symbol, #[subdiagnostic] @@ -43,32 +48,36 @@ pub struct CrateDepMultiple { } #[derive(Subdiagnostic)] -#[note(metadata_crate_dep_not_static)] +#[note("`{$crate_name}` was unavailable as a static crate, preventing fully static linking")] pub struct NonStaticCrateDep { /// It's different from `crate_name` in main Diagnostic. pub crate_name_: Symbol, } #[derive(Subdiagnostic)] -#[help(metadata_crate_dep_rustc_driver)] +#[help("`feature(rustc_private)` is needed to link to the compiler's `rustc_driver` library")] pub struct RustcDriverHelp; #[derive(Diagnostic)] -#[diag(metadata_two_panic_runtimes)] +#[diag("cannot link together two panic runtimes: {$prev_name} and {$cur_name}")] pub struct TwoPanicRuntimes { pub prev_name: Symbol, pub cur_name: Symbol, } #[derive(Diagnostic)] -#[diag(metadata_bad_panic_strategy)] +#[diag( + "the linked panic runtime `{$runtime}` is not compiled with this crate's panic strategy `{$strategy}`" +)] pub struct BadPanicStrategy { pub runtime: Symbol, pub strategy: PanicStrategy, } #[derive(Diagnostic)] -#[diag(metadata_required_panic_strategy)] +#[diag( + "the crate `{$crate_name}` requires panic strategy `{$found_strategy}` which is incompatible with this crate's strategy of `{$desired_strategy}`" +)] pub struct RequiredPanicStrategy { pub crate_name: Symbol, pub found_strategy: PanicStrategy, @@ -76,17 +85,23 @@ pub struct RequiredPanicStrategy { } #[derive(Diagnostic)] -#[diag(metadata_incompatible_with_immediate_abort)] +#[diag( + "the crate `{$crate_name}` was compiled with a panic strategy which is incompatible with `immediate-abort`" +)] pub struct IncompatibleWithImmediateAbort { pub crate_name: Symbol, } #[derive(Diagnostic)] -#[diag(metadata_incompatible_with_immediate_abort_core)] +#[diag( + "the crate `core` was compiled with a panic strategy which is incompatible with `immediate-abort`" +)] pub struct IncompatibleWithImmediateAbortCore; #[derive(Diagnostic)] -#[diag(metadata_incompatible_panic_in_drop_strategy)] +#[diag( + "the crate `{$crate_name}` is compiled with the panic-in-drop strategy `{$found_strategy}` which is incompatible with this crate's strategy of `{$desired_strategy}`" +)] pub struct IncompatiblePanicInDropStrategy { pub crate_name: Symbol, pub found_strategy: PanicStrategy, @@ -94,126 +109,138 @@ pub struct IncompatiblePanicInDropStrategy { } #[derive(Diagnostic)] -#[diag(metadata_link_ordinal_raw_dylib)] +#[diag("`#[link_ordinal]` is only supported if link kind is `raw-dylib`")] pub struct LinkOrdinalRawDylib { #[primary_span] pub span: Span, } #[derive(Diagnostic)] -#[diag(metadata_lib_framework_apple)] +#[diag("library kind `framework` is only supported on Apple targets")] pub struct LibFrameworkApple; #[derive(Diagnostic)] -#[diag(metadata_empty_renaming_target)] +#[diag("an empty renaming target was specified for library `{$lib_name}`")] pub struct EmptyRenamingTarget<'a> { pub lib_name: &'a str, } #[derive(Diagnostic)] -#[diag(metadata_renaming_no_link)] +#[diag( + "renaming of the library `{$lib_name}` was specified, however this crate contains no `#[link(...)]` attributes referencing this library" +)] pub struct RenamingNoLink<'a> { pub lib_name: &'a str, } #[derive(Diagnostic)] -#[diag(metadata_multiple_renamings)] +#[diag("multiple renamings were specified for library `{$lib_name}`")] pub struct MultipleRenamings<'a> { pub lib_name: &'a str, } #[derive(Diagnostic)] -#[diag(metadata_no_link_mod_override)] +#[diag("overriding linking modifiers from command line is not supported")] pub struct NoLinkModOverride { #[primary_span] pub span: Option, } #[derive(Diagnostic)] -#[diag(metadata_raw_dylib_unsupported_abi)] +#[diag("ABI not supported by `#[link(kind = \"raw-dylib\")]` on this architecture")] pub struct RawDylibUnsupportedAbi { #[primary_span] pub span: Span, } #[derive(Diagnostic)] -#[diag(metadata_fail_create_file_encoder)] +#[diag("failed to create file encoder: {$err}")] pub struct FailCreateFileEncoder { pub err: Error, } #[derive(Diagnostic)] -#[diag(metadata_fail_write_file)] +#[diag("failed to write to `{$path}`: {$err}")] pub struct FailWriteFile<'a> { pub path: &'a Path, pub err: Error, } #[derive(Diagnostic)] -#[diag(metadata_crate_not_panic_runtime)] +#[diag("the crate `{$crate_name}` is not a panic runtime")] pub struct CrateNotPanicRuntime { pub crate_name: Symbol, } #[derive(Diagnostic)] -#[diag(metadata_crate_not_compiler_builtins)] +#[diag( + "the crate `{$crate_name}` resolved as `compiler_builtins` but is not `#![compiler_builtins]`" +)] pub struct CrateNotCompilerBuiltins { pub crate_name: Symbol, } #[derive(Diagnostic)] -#[diag(metadata_no_panic_strategy)] +#[diag("the crate `{$crate_name}` does not have the panic strategy `{$strategy}`")] pub struct NoPanicStrategy { pub crate_name: Symbol, pub strategy: PanicStrategy, } #[derive(Diagnostic)] -#[diag(metadata_not_profiler_runtime)] +#[diag("the crate `{$crate_name}` is not a profiler runtime")] pub struct NotProfilerRuntime { pub crate_name: Symbol, } #[derive(Diagnostic)] -#[diag(metadata_no_multiple_global_alloc)] +#[diag("cannot define multiple global allocators")] pub struct NoMultipleGlobalAlloc { #[primary_span] - #[label] + #[label("cannot define a new global allocator")] pub span2: Span, - #[label(metadata_prev_global_alloc)] + #[label("previous global allocator defined here")] pub span1: Span, } #[derive(Diagnostic)] -#[diag(metadata_no_multiple_alloc_error_handler)] +#[diag("cannot define multiple allocation error handlers")] pub struct NoMultipleAllocErrorHandler { #[primary_span] - #[label] + #[label("cannot define a new allocation error handler")] pub span2: Span, - #[label(metadata_prev_alloc_error_handler)] + #[label("previous allocation error handler defined here")] pub span1: Span, } #[derive(Diagnostic)] -#[diag(metadata_conflicting_global_alloc)] +#[diag( + "the `#[global_allocator]` in {$other_crate_name} conflicts with global allocator in: {$crate_name}" +)] pub struct ConflictingGlobalAlloc { pub crate_name: Symbol, pub other_crate_name: Symbol, } #[derive(Diagnostic)] -#[diag(metadata_conflicting_alloc_error_handler)] +#[diag( + "the `#[alloc_error_handler]` in {$other_crate_name} conflicts with allocation error handler in: {$crate_name}" +)] pub struct ConflictingAllocErrorHandler { pub crate_name: Symbol, pub other_crate_name: Symbol, } #[derive(Diagnostic)] -#[diag(metadata_global_alloc_required)] +#[diag( + "no global memory allocator found but one is required; link to std or add `#[global_allocator]` to a static item that implements the GlobalAlloc trait" +)] pub struct GlobalAllocRequired; #[derive(Diagnostic)] -#[diag(metadata_no_transitive_needs_dep)] +#[diag( + "the crate `{$crate_name}` cannot depend on a crate that needs {$needs_crate_name}, but it depends on `{$deps_crate_name}`" +)] pub struct NoTransitiveNeedsDep<'a> { pub crate_name: Symbol, pub needs_crate_name: &'a str, @@ -221,25 +248,27 @@ pub struct NoTransitiveNeedsDep<'a> { } #[derive(Diagnostic)] -#[diag(metadata_failed_write_error)] +#[diag("failed to write {$filename}: {$err}")] pub struct FailedWriteError { pub filename: PathBuf, pub err: Error, } #[derive(Diagnostic)] -#[diag(metadata_failed_copy_to_stdout)] +#[diag("failed to copy {$filename} to stdout: {$err}")] pub struct FailedCopyToStdout { pub filename: PathBuf, pub err: Error, } #[derive(Diagnostic)] -#[diag(metadata_binary_output_to_tty)] +#[diag( + "option `-o` or `--emit` is used to write binary output type `metadata` to stdout, but stdout is a tty" +)] pub struct BinaryOutputToTty; #[derive(Diagnostic)] -#[diag(metadata_missing_native_library)] +#[diag("could not find native static library `{$libname}`, perhaps an -L flag is missing?")] pub struct MissingNativeLibrary<'a> { libname: &'a str, #[subdiagnostic] @@ -273,32 +302,32 @@ impl<'a> MissingNativeLibrary<'a> { } #[derive(Subdiagnostic)] -#[help(metadata_only_provide_library_name)] +#[help("only provide the library name `{$suggested_name}`, not the full filename")] pub struct SuggestLibraryName<'a> { suggested_name: &'a str, } #[derive(Diagnostic)] -#[diag(metadata_failed_create_tempdir)] +#[diag("couldn't create a temp dir: {$err}")] pub struct FailedCreateTempdir { pub err: Error, } #[derive(Diagnostic)] -#[diag(metadata_failed_create_file)] +#[diag("failed to create the file {$filename}: {$err}")] pub struct FailedCreateFile<'a> { pub filename: &'a Path, pub err: Error, } #[derive(Diagnostic)] -#[diag(metadata_failed_create_encoded_metadata)] +#[diag("failed to create encoded metadata from file: {$err}")] pub struct FailedCreateEncodedMetadata { pub err: Error, } #[derive(Diagnostic)] -#[diag(metadata_non_ascii_name)] +#[diag("cannot load a crate with a non-ascii name `{$crate_name}`")] pub struct NonAsciiName { #[primary_span] pub span: Span, @@ -306,7 +335,7 @@ pub struct NonAsciiName { } #[derive(Diagnostic)] -#[diag(metadata_extern_location_not_exist)] +#[diag("extern location for {$crate_name} does not exist: {$location}")] pub struct ExternLocationNotExist<'a> { #[primary_span] pub span: Span, @@ -315,7 +344,7 @@ pub struct ExternLocationNotExist<'a> { } #[derive(Diagnostic)] -#[diag(metadata_extern_location_not_file)] +#[diag("extern location for {$crate_name} is not a file: {$location}")] pub struct ExternLocationNotFile<'a> { #[primary_span] pub span: Span, @@ -332,7 +361,11 @@ pub(crate) struct MultipleCandidates { impl Diagnostic<'_, G> for MultipleCandidates { fn into_diag(self, dcx: DiagCtxtHandle<'_>, level: Level) -> Diag<'_, G> { - let mut diag = Diag::new(dcx, level, fluent::metadata_multiple_candidates); + let mut diag = Diag::new( + dcx, + level, + inline_fluent!("multiple candidates for `{$flavor}` dependency `{$crate_name}` found"), + ); diag.arg("crate_name", self.crate_name); diag.arg("flavor", self.flavor); diag.code(E0464); @@ -345,7 +378,9 @@ impl Diagnostic<'_, G> for MultipleCandidates { } #[derive(Diagnostic)] -#[diag(metadata_full_metadata_not_found)] +#[diag( + "only metadata stub found for `{$flavor}` dependency `{$crate_name}` please provide path to the corresponding .rmeta file with full metadata" +)] pub(crate) struct FullMetadataNotFound { #[primary_span] pub span: Span, @@ -354,7 +389,7 @@ pub(crate) struct FullMetadataNotFound { } #[derive(Diagnostic)] -#[diag(metadata_symbol_conflicts_current, code = E0519)] +#[diag("the current crate is indistinguishable from one of its dependencies: it has the same crate-name `{$crate_name}` and was compiled with the same `-C metadata` arguments, so this will result in symbol conflicts between the two", code = E0519)] pub struct SymbolConflictsCurrent { #[primary_span] pub span: Span, @@ -362,7 +397,7 @@ pub struct SymbolConflictsCurrent { } #[derive(Diagnostic)] -#[diag(metadata_stable_crate_id_collision)] +#[diag("found crates (`{$crate_name0}` and `{$crate_name1}`) with colliding StableCrateId values")] pub struct StableCrateIdCollision { #[primary_span] pub span: Span, @@ -371,7 +406,7 @@ pub struct StableCrateIdCollision { } #[derive(Diagnostic)] -#[diag(metadata_dl_error)] +#[diag("{$path}{$err}")] pub struct DlError { #[primary_span] pub span: Span, @@ -380,9 +415,9 @@ pub struct DlError { } #[derive(Diagnostic)] -#[diag(metadata_newer_crate_version, code = E0460)] -#[note] -#[note(metadata_found_crate_versions)] +#[diag("found possibly newer version of crate `{$crate_name}`{$add_info}", code = E0460)] +#[note("perhaps that crate needs to be recompiled?")] +#[note("the following crate versions were found:{$found_crates}")] pub struct NewerCrateVersion { #[primary_span] pub span: Span, @@ -392,8 +427,8 @@ pub struct NewerCrateVersion { } #[derive(Diagnostic)] -#[diag(metadata_no_crate_with_triple, code = E0461)] -#[note(metadata_found_crate_versions)] +#[diag("couldn't find crate `{$crate_name}` with expected target triple {$locator_triple}{$add_info}", code = E0461)] +#[note("the following crate versions were found:{$found_crates}")] pub struct NoCrateWithTriple<'a> { #[primary_span] pub span: Span, @@ -404,9 +439,9 @@ pub struct NoCrateWithTriple<'a> { } #[derive(Diagnostic)] -#[diag(metadata_found_staticlib, code = E0462)] -#[note(metadata_found_crate_versions)] -#[help] +#[diag("found staticlib `{$crate_name}` instead of rlib or dylib{$add_info}", code = E0462)] +#[note("the following crate versions were found:{$found_crates}")] +#[help("please recompile that crate using --crate-type lib")] pub struct FoundStaticlib { #[primary_span] pub span: Span, @@ -416,9 +451,11 @@ pub struct FoundStaticlib { } #[derive(Diagnostic)] -#[diag(metadata_incompatible_rustc, code = E0514)] -#[note(metadata_found_crate_versions)] -#[help] +#[diag("found crate `{$crate_name}` compiled by an incompatible version of rustc{$add_info}", code = E0514)] +#[note("the following crate versions were found:{$found_crates}")] +#[help( + "please recompile that crate using this compiler ({$rustc_version}) (consider running `cargo clean` first)" +)] pub struct IncompatibleRustc { #[primary_span] pub span: Span, @@ -438,7 +475,11 @@ pub struct InvalidMetadataFiles { impl Diagnostic<'_, G> for InvalidMetadataFiles { #[track_caller] fn into_diag(self, dcx: DiagCtxtHandle<'_>, level: Level) -> Diag<'_, G> { - let mut diag = Diag::new(dcx, level, fluent::metadata_invalid_meta_files); + let mut diag = Diag::new( + dcx, + level, + inline_fluent!("found invalid metadata files for crate `{$crate_name}`{$add_info}"), + ); diag.arg("crate_name", self.crate_name); diag.arg("add_info", self.add_info); diag.code(E0786); @@ -466,7 +507,11 @@ pub struct CannotFindCrate { impl Diagnostic<'_, G> for CannotFindCrate { #[track_caller] fn into_diag(self, dcx: DiagCtxtHandle<'_>, level: Level) -> Diag<'_, G> { - let mut diag = Diag::new(dcx, level, fluent::metadata_cannot_find_crate); + let mut diag = Diag::new( + dcx, + level, + inline_fluent!("can't find crate for `{$crate_name}`{$add_info}"), + ); diag.arg("crate_name", self.crate_name); diag.arg("current_crate", self.current_crate); diag.arg("add_info", self.add_info); @@ -475,9 +520,11 @@ impl Diagnostic<'_, G> for CannotFindCrate { diag.span(self.span); if self.crate_name == sym::std || self.crate_name == sym::core { if self.missing_core { - diag.note(fluent::metadata_target_not_installed); + diag.note(inline_fluent!("the `{$locator_triple}` target may not be installed")); } else { - diag.note(fluent::metadata_target_no_std_support); + diag.note(inline_fluent!( + "the `{$locator_triple}` target may not support the standard library" + )); } let has_precompiled_std = !self.is_tier_3; @@ -485,12 +532,14 @@ impl Diagnostic<'_, G> for CannotFindCrate { if self.missing_core { if env!("CFG_RELEASE_CHANNEL") == "dev" && !self.is_ui_testing { // Note: Emits the nicer suggestion only for the dev channel. - diag.help(fluent::metadata_consider_adding_std); + diag.help(inline_fluent!("consider adding the standard library to the sysroot with `x build library --target {$locator_triple}`")); } else if has_precompiled_std { // NOTE: this suggests using rustup, even though the user may not have it installed. // That's because they could choose to install it; or this may give them a hint which // target they need to install from their distro. - diag.help(fluent::metadata_consider_downloading_target); + diag.help(inline_fluent!( + "consider downloading the target with `rustup target add {$locator_triple}`" + )); } } @@ -499,25 +548,27 @@ impl Diagnostic<'_, G> for CannotFindCrate { // If it's not a dummy, that means someone added `extern crate std` explicitly and // `#![no_std]` won't help. if !self.missing_core && self.span.is_dummy() { - diag.note(fluent::metadata_std_required); + diag.note(inline_fluent!("`std` is required by `{$current_crate}` because it does not declare `#![no_std]`")); } // Recommend -Zbuild-std even on stable builds for Tier 3 targets because // it's the recommended way to use the target, the user should switch to nightly. if self.is_nightly_build || !has_precompiled_std { - diag.help(fluent::metadata_consider_building_std); + diag.help(inline_fluent!("consider building the standard library from source with `cargo build -Zbuild-std`")); } } else if self.crate_name == self.profiler_runtime { - diag.note(fluent::metadata_compiler_missing_profiler); + diag.note(inline_fluent!( + "the compiler may have been built without the profiler runtime" + )); } else if self.crate_name.as_str().starts_with("rustc_") { - diag.help(fluent::metadata_install_missing_components); + diag.help(inline_fluent!("maybe you need to install the missing components with: `rustup component add rust-src rustc-dev llvm-tools-preview`")); } - diag.span_label(self.span, fluent::metadata_cant_find_crate); + diag.span_label(self.span, inline_fluent!("can't find crate")); diag } } #[derive(Diagnostic)] -#[diag(metadata_crate_location_unknown_type)] +#[diag("extern location for {$crate_name} is of an unknown type: {$path}")] pub struct CrateLocationUnknownType<'a> { #[primary_span] pub span: Span, @@ -526,7 +577,7 @@ pub struct CrateLocationUnknownType<'a> { } #[derive(Diagnostic)] -#[diag(metadata_lib_filename_form)] +#[diag("file name should be lib*.rlib or {$dll_prefix}*{$dll_suffix}")] pub struct LibFilenameForm<'a> { #[primary_span] pub span: Span, @@ -535,18 +586,28 @@ pub struct LibFilenameForm<'a> { } #[derive(Diagnostic)] -#[diag(metadata_wasm_c_abi)] +#[diag( + "older versions of the `wasm-bindgen` crate are incompatible with current versions of Rust; please update to `wasm-bindgen` v0.2.88" +)] pub(crate) struct WasmCAbi { #[primary_span] pub span: Span, } #[derive(Diagnostic)] -#[diag(metadata_incompatible_target_modifiers)] -#[help] -#[note] -#[help(metadata_incompatible_target_modifiers_help_fix)] -#[help(metadata_incompatible_target_modifiers_help_allow)] +#[diag("mixing `{$flag_name_prefixed}` will cause an ABI mismatch in crate `{$local_crate}`")] +#[help( + "the `{$flag_name_prefixed}` flag modifies the ABI so Rust crates compiled with different values of this flag cannot be used together safely" +)] +#[note( + "`{$flag_name_prefixed}={$local_value}` in this crate is incompatible with `{$flag_name_prefixed}={$extern_value}` in dependency `{$extern_crate}`" +)] +#[help( + "set `{$flag_name_prefixed}={$extern_value}` in this crate or `{$flag_name_prefixed}={$local_value}` in `{$extern_crate}`" +)] +#[help( + "if you are sure this will not cause problems, you may use `-Cunsafe-allow-abi-mismatch={$flag_name}` to silence this error" +)] pub struct IncompatibleTargetModifiers { #[primary_span] pub span: Span, @@ -559,11 +620,19 @@ pub struct IncompatibleTargetModifiers { } #[derive(Diagnostic)] -#[diag(metadata_incompatible_target_modifiers_l_missed)] -#[help] -#[note] -#[help(metadata_incompatible_target_modifiers_help_fix_l_missed)] -#[help(metadata_incompatible_target_modifiers_help_allow)] +#[diag("mixing `{$flag_name_prefixed}` will cause an ABI mismatch in crate `{$local_crate}`")] +#[help( + "the `{$flag_name_prefixed}` flag modifies the ABI so Rust crates compiled with different values of this flag cannot be used together safely" +)] +#[note( + "unset `{$flag_name_prefixed}` in this crate is incompatible with `{$flag_name_prefixed}={$extern_value}` in dependency `{$extern_crate}`" +)] +#[help( + "set `{$flag_name_prefixed}={$extern_value}` in this crate or unset `{$flag_name_prefixed}` in `{$extern_crate}`" +)] +#[help( + "if you are sure this will not cause problems, you may use `-Cunsafe-allow-abi-mismatch={$flag_name}` to silence this error" +)] pub struct IncompatibleTargetModifiersLMissed { #[primary_span] pub span: Span, @@ -575,11 +644,19 @@ pub struct IncompatibleTargetModifiersLMissed { } #[derive(Diagnostic)] -#[diag(metadata_incompatible_target_modifiers_r_missed)] -#[help] -#[note] -#[help(metadata_incompatible_target_modifiers_help_fix_r_missed)] -#[help(metadata_incompatible_target_modifiers_help_allow)] +#[diag("mixing `{$flag_name_prefixed}` will cause an ABI mismatch in crate `{$local_crate}`")] +#[help( + "the `{$flag_name_prefixed}` flag modifies the ABI so Rust crates compiled with different values of this flag cannot be used together safely" +)] +#[note( + "`{$flag_name_prefixed}={$local_value}` in this crate is incompatible with unset `{$flag_name_prefixed}` in dependency `{$extern_crate}`" +)] +#[help( + "unset `{$flag_name_prefixed}` in this crate or set `{$flag_name_prefixed}={$local_value}` in `{$extern_crate}`" +)] +#[help( + "if you are sure this will not cause problems, you may use `-Cunsafe-allow-abi-mismatch={$flag_name}` to silence this error" +)] pub struct IncompatibleTargetModifiersRMissed { #[primary_span] pub span: Span, @@ -591,7 +668,9 @@ pub struct IncompatibleTargetModifiersRMissed { } #[derive(Diagnostic)] -#[diag(metadata_unknown_target_modifier_unsafe_allowed)] +#[diag( + "unknown target modifier `{$flag_name}`, requested by `-Cunsafe-allow-abi-mismatch={$flag_name}`" +)] pub struct UnknownTargetModifierUnsafeAllowed { #[primary_span] pub span: Span, @@ -599,8 +678,12 @@ pub struct UnknownTargetModifierUnsafeAllowed { } #[derive(Diagnostic)] -#[diag(metadata_async_drop_types_in_dependency)] -#[help] +#[diag( + "found async drop types in dependency `{$extern_crate}`, but async_drop feature is disabled for `{$local_crate}`" +)] +#[help( + "if async drop type will be dropped in a crate without `feature(async_drop)`, sync Drop will be used" +)] pub struct AsyncDropTypesInDependency { #[primary_span] pub span: Span, @@ -609,7 +692,7 @@ pub struct AsyncDropTypesInDependency { } #[derive(Diagnostic)] -#[diag(metadata_raw_dylib_malformed)] +#[diag("link name must be well-formed if link kind is `raw-dylib`")] pub struct RawDylibMalformed { #[primary_span] pub span: Span, diff --git a/compiler/rustc_metadata/src/lib.rs b/compiler/rustc_metadata/src/lib.rs index f3b738f93d2d7..22c8a0c4cd7ee 100644 --- a/compiler/rustc_metadata/src/lib.rs +++ b/compiler/rustc_metadata/src/lib.rs @@ -34,5 +34,3 @@ pub use native_libs::{ try_find_native_static_library, walk_native_lib_search_dirs, }; pub use rmeta::{EncodedMetadata, METADATA_HEADER, encode_metadata, rendered_const}; - -rustc_fluent_macro::fluent_messages! { "../messages.ftl" } diff --git a/compiler/rustc_middle/src/dep_graph/dep_node.rs b/compiler/rustc_middle/src/dep_graph/dep_node.rs index f5ed0570667cc..5f90d1b67d9de 100644 --- a/compiler/rustc_middle/src/dep_graph/dep_node.rs +++ b/compiler/rustc_middle/src/dep_graph/dep_node.rs @@ -1,11 +1,7 @@ -use rustc_data_structures::fingerprint::Fingerprint; -use rustc_hir::def_id::{CrateNum, DefId, LOCAL_CRATE, LocalDefId, LocalModDefId, ModDefId}; +use rustc_hir::def_id::DefId; use rustc_hir::definitions::DefPathHash; -use rustc_hir::{HirId, ItemLocalId, OwnerId}; -pub use rustc_query_system::dep_graph::DepNode; -use rustc_query_system::dep_graph::FingerprintStyle; -pub use rustc_query_system::dep_graph::dep_node::DepKind; -pub(crate) use rustc_query_system::dep_graph::{DepContext, DepNodeParams}; +use rustc_query_system::dep_graph::dep_node::DepKind; +use rustc_query_system::dep_graph::{DepContext, DepNode, FingerprintStyle}; use rustc_span::Symbol; use crate::mir::mono::MonoItem; @@ -176,223 +172,3 @@ pub fn dep_kind_from_label(label: &str) -> DepKind { dep_kind_from_label_string(label) .unwrap_or_else(|_| panic!("Query label {label} does not exist")) } - -impl<'tcx> DepNodeParams> for () { - #[inline(always)] - fn fingerprint_style() -> FingerprintStyle { - FingerprintStyle::Unit - } - - #[inline(always)] - fn to_fingerprint(&self, _: TyCtxt<'tcx>) -> Fingerprint { - Fingerprint::ZERO - } - - #[inline(always)] - fn recover(_: TyCtxt<'tcx>, _: &DepNode) -> Option { - Some(()) - } -} - -impl<'tcx> DepNodeParams> for DefId { - #[inline(always)] - fn fingerprint_style() -> FingerprintStyle { - FingerprintStyle::DefPathHash - } - - #[inline(always)] - fn to_fingerprint(&self, tcx: TyCtxt<'tcx>) -> Fingerprint { - tcx.def_path_hash(*self).0 - } - - #[inline(always)] - fn to_debug_str(&self, tcx: TyCtxt<'tcx>) -> String { - tcx.def_path_str(*self) - } - - #[inline(always)] - fn recover(tcx: TyCtxt<'tcx>, dep_node: &DepNode) -> Option { - dep_node.extract_def_id(tcx) - } -} - -impl<'tcx> DepNodeParams> for LocalDefId { - #[inline(always)] - fn fingerprint_style() -> FingerprintStyle { - FingerprintStyle::DefPathHash - } - - #[inline(always)] - fn to_fingerprint(&self, tcx: TyCtxt<'tcx>) -> Fingerprint { - self.to_def_id().to_fingerprint(tcx) - } - - #[inline(always)] - fn to_debug_str(&self, tcx: TyCtxt<'tcx>) -> String { - self.to_def_id().to_debug_str(tcx) - } - - #[inline(always)] - fn recover(tcx: TyCtxt<'tcx>, dep_node: &DepNode) -> Option { - dep_node.extract_def_id(tcx).map(|id| id.expect_local()) - } -} - -impl<'tcx> DepNodeParams> for OwnerId { - #[inline(always)] - fn fingerprint_style() -> FingerprintStyle { - FingerprintStyle::DefPathHash - } - - #[inline(always)] - fn to_fingerprint(&self, tcx: TyCtxt<'tcx>) -> Fingerprint { - self.to_def_id().to_fingerprint(tcx) - } - - #[inline(always)] - fn to_debug_str(&self, tcx: TyCtxt<'tcx>) -> String { - self.to_def_id().to_debug_str(tcx) - } - - #[inline(always)] - fn recover(tcx: TyCtxt<'tcx>, dep_node: &DepNode) -> Option { - dep_node.extract_def_id(tcx).map(|id| OwnerId { def_id: id.expect_local() }) - } -} - -impl<'tcx> DepNodeParams> for CrateNum { - #[inline(always)] - fn fingerprint_style() -> FingerprintStyle { - FingerprintStyle::DefPathHash - } - - #[inline(always)] - fn to_fingerprint(&self, tcx: TyCtxt<'tcx>) -> Fingerprint { - let def_id = self.as_def_id(); - def_id.to_fingerprint(tcx) - } - - #[inline(always)] - fn to_debug_str(&self, tcx: TyCtxt<'tcx>) -> String { - tcx.crate_name(*self).to_string() - } - - #[inline(always)] - fn recover(tcx: TyCtxt<'tcx>, dep_node: &DepNode) -> Option { - dep_node.extract_def_id(tcx).map(|id| id.krate) - } -} - -impl<'tcx> DepNodeParams> for (DefId, DefId) { - #[inline(always)] - fn fingerprint_style() -> FingerprintStyle { - FingerprintStyle::Opaque - } - - // We actually would not need to specialize the implementation of this - // method but it's faster to combine the hashes than to instantiate a full - // hashing context and stable-hashing state. - #[inline(always)] - fn to_fingerprint(&self, tcx: TyCtxt<'tcx>) -> Fingerprint { - let (def_id_0, def_id_1) = *self; - - let def_path_hash_0 = tcx.def_path_hash(def_id_0); - let def_path_hash_1 = tcx.def_path_hash(def_id_1); - - def_path_hash_0.0.combine(def_path_hash_1.0) - } - - #[inline(always)] - fn to_debug_str(&self, tcx: TyCtxt<'tcx>) -> String { - let (def_id_0, def_id_1) = *self; - - format!("({}, {})", tcx.def_path_debug_str(def_id_0), tcx.def_path_debug_str(def_id_1)) - } -} - -impl<'tcx> DepNodeParams> for HirId { - #[inline(always)] - fn fingerprint_style() -> FingerprintStyle { - FingerprintStyle::HirId - } - - // We actually would not need to specialize the implementation of this - // method but it's faster to combine the hashes than to instantiate a full - // hashing context and stable-hashing state. - #[inline(always)] - fn to_fingerprint(&self, tcx: TyCtxt<'tcx>) -> Fingerprint { - let HirId { owner, local_id } = *self; - let def_path_hash = tcx.def_path_hash(owner.to_def_id()); - Fingerprint::new( - // `owner` is local, so is completely defined by the local hash - def_path_hash.local_hash(), - local_id.as_u32() as u64, - ) - } - - #[inline(always)] - fn to_debug_str(&self, tcx: TyCtxt<'tcx>) -> String { - let HirId { owner, local_id } = *self; - format!("{}.{}", tcx.def_path_str(owner), local_id.as_u32()) - } - - #[inline(always)] - fn recover(tcx: TyCtxt<'tcx>, dep_node: &DepNode) -> Option { - if tcx.fingerprint_style(dep_node.kind) == FingerprintStyle::HirId { - let (local_hash, local_id) = Fingerprint::from(dep_node.hash).split(); - let def_path_hash = DefPathHash::new(tcx.stable_crate_id(LOCAL_CRATE), local_hash); - let def_id = tcx.def_path_hash_to_def_id(def_path_hash)?.expect_local(); - let local_id = local_id - .as_u64() - .try_into() - .unwrap_or_else(|_| panic!("local id should be u32, found {local_id:?}")); - Some(HirId { owner: OwnerId { def_id }, local_id: ItemLocalId::from_u32(local_id) }) - } else { - None - } - } -} - -impl<'tcx> DepNodeParams> for ModDefId { - #[inline(always)] - fn fingerprint_style() -> FingerprintStyle { - FingerprintStyle::DefPathHash - } - - #[inline(always)] - fn to_fingerprint(&self, tcx: TyCtxt<'tcx>) -> Fingerprint { - self.to_def_id().to_fingerprint(tcx) - } - - #[inline(always)] - fn to_debug_str(&self, tcx: TyCtxt<'tcx>) -> String { - self.to_def_id().to_debug_str(tcx) - } - - #[inline(always)] - fn recover(tcx: TyCtxt<'tcx>, dep_node: &DepNode) -> Option { - DefId::recover(tcx, dep_node).map(ModDefId::new_unchecked) - } -} - -impl<'tcx> DepNodeParams> for LocalModDefId { - #[inline(always)] - fn fingerprint_style() -> FingerprintStyle { - FingerprintStyle::DefPathHash - } - - #[inline(always)] - fn to_fingerprint(&self, tcx: TyCtxt<'tcx>) -> Fingerprint { - self.to_def_id().to_fingerprint(tcx) - } - - #[inline(always)] - fn to_debug_str(&self, tcx: TyCtxt<'tcx>) -> String { - self.to_def_id().to_debug_str(tcx) - } - - #[inline(always)] - fn recover(tcx: TyCtxt<'tcx>, dep_node: &DepNode) -> Option { - LocalDefId::recover(tcx, dep_node).map(LocalModDefId::new_unchecked) - } -} diff --git a/compiler/rustc_middle/src/dep_graph/dep_node_key.rs b/compiler/rustc_middle/src/dep_graph/dep_node_key.rs new file mode 100644 index 0000000000000..e2fcd82c896ad --- /dev/null +++ b/compiler/rustc_middle/src/dep_graph/dep_node_key.rs @@ -0,0 +1,228 @@ +use rustc_data_structures::fingerprint::Fingerprint; +use rustc_hir::def_id::{CrateNum, DefId, LOCAL_CRATE, LocalDefId, LocalModDefId, ModDefId}; +use rustc_hir::definitions::DefPathHash; +use rustc_hir::{HirId, ItemLocalId, OwnerId}; +use rustc_query_system::dep_graph::{DepContext, DepNode, DepNodeKey, FingerprintStyle}; + +use crate::dep_graph::DepNodeExt; +use crate::ty::TyCtxt; + +impl<'tcx> DepNodeKey> for () { + #[inline(always)] + fn fingerprint_style() -> FingerprintStyle { + FingerprintStyle::Unit + } + + #[inline(always)] + fn to_fingerprint(&self, _: TyCtxt<'tcx>) -> Fingerprint { + Fingerprint::ZERO + } + + #[inline(always)] + fn recover(_: TyCtxt<'tcx>, _: &DepNode) -> Option { + Some(()) + } +} + +impl<'tcx> DepNodeKey> for DefId { + #[inline(always)] + fn fingerprint_style() -> FingerprintStyle { + FingerprintStyle::DefPathHash + } + + #[inline(always)] + fn to_fingerprint(&self, tcx: TyCtxt<'tcx>) -> Fingerprint { + tcx.def_path_hash(*self).0 + } + + #[inline(always)] + fn to_debug_str(&self, tcx: TyCtxt<'tcx>) -> String { + tcx.def_path_str(*self) + } + + #[inline(always)] + fn recover(tcx: TyCtxt<'tcx>, dep_node: &DepNode) -> Option { + dep_node.extract_def_id(tcx) + } +} + +impl<'tcx> DepNodeKey> for LocalDefId { + #[inline(always)] + fn fingerprint_style() -> FingerprintStyle { + FingerprintStyle::DefPathHash + } + + #[inline(always)] + fn to_fingerprint(&self, tcx: TyCtxt<'tcx>) -> Fingerprint { + self.to_def_id().to_fingerprint(tcx) + } + + #[inline(always)] + fn to_debug_str(&self, tcx: TyCtxt<'tcx>) -> String { + self.to_def_id().to_debug_str(tcx) + } + + #[inline(always)] + fn recover(tcx: TyCtxt<'tcx>, dep_node: &DepNode) -> Option { + dep_node.extract_def_id(tcx).map(|id| id.expect_local()) + } +} + +impl<'tcx> DepNodeKey> for OwnerId { + #[inline(always)] + fn fingerprint_style() -> FingerprintStyle { + FingerprintStyle::DefPathHash + } + + #[inline(always)] + fn to_fingerprint(&self, tcx: TyCtxt<'tcx>) -> Fingerprint { + self.to_def_id().to_fingerprint(tcx) + } + + #[inline(always)] + fn to_debug_str(&self, tcx: TyCtxt<'tcx>) -> String { + self.to_def_id().to_debug_str(tcx) + } + + #[inline(always)] + fn recover(tcx: TyCtxt<'tcx>, dep_node: &DepNode) -> Option { + dep_node.extract_def_id(tcx).map(|id| OwnerId { def_id: id.expect_local() }) + } +} + +impl<'tcx> DepNodeKey> for CrateNum { + #[inline(always)] + fn fingerprint_style() -> FingerprintStyle { + FingerprintStyle::DefPathHash + } + + #[inline(always)] + fn to_fingerprint(&self, tcx: TyCtxt<'tcx>) -> Fingerprint { + let def_id = self.as_def_id(); + def_id.to_fingerprint(tcx) + } + + #[inline(always)] + fn to_debug_str(&self, tcx: TyCtxt<'tcx>) -> String { + tcx.crate_name(*self).to_string() + } + + #[inline(always)] + fn recover(tcx: TyCtxt<'tcx>, dep_node: &DepNode) -> Option { + dep_node.extract_def_id(tcx).map(|id| id.krate) + } +} + +impl<'tcx> DepNodeKey> for (DefId, DefId) { + #[inline(always)] + fn fingerprint_style() -> FingerprintStyle { + FingerprintStyle::Opaque + } + + // We actually would not need to specialize the implementation of this + // method but it's faster to combine the hashes than to instantiate a full + // hashing context and stable-hashing state. + #[inline(always)] + fn to_fingerprint(&self, tcx: TyCtxt<'tcx>) -> Fingerprint { + let (def_id_0, def_id_1) = *self; + + let def_path_hash_0 = tcx.def_path_hash(def_id_0); + let def_path_hash_1 = tcx.def_path_hash(def_id_1); + + def_path_hash_0.0.combine(def_path_hash_1.0) + } + + #[inline(always)] + fn to_debug_str(&self, tcx: TyCtxt<'tcx>) -> String { + let (def_id_0, def_id_1) = *self; + + format!("({}, {})", tcx.def_path_debug_str(def_id_0), tcx.def_path_debug_str(def_id_1)) + } +} + +impl<'tcx> DepNodeKey> for HirId { + #[inline(always)] + fn fingerprint_style() -> FingerprintStyle { + FingerprintStyle::HirId + } + + // We actually would not need to specialize the implementation of this + // method but it's faster to combine the hashes than to instantiate a full + // hashing context and stable-hashing state. + #[inline(always)] + fn to_fingerprint(&self, tcx: TyCtxt<'tcx>) -> Fingerprint { + let HirId { owner, local_id } = *self; + let def_path_hash = tcx.def_path_hash(owner.to_def_id()); + Fingerprint::new( + // `owner` is local, so is completely defined by the local hash + def_path_hash.local_hash(), + local_id.as_u32() as u64, + ) + } + + #[inline(always)] + fn to_debug_str(&self, tcx: TyCtxt<'tcx>) -> String { + let HirId { owner, local_id } = *self; + format!("{}.{}", tcx.def_path_str(owner), local_id.as_u32()) + } + + #[inline(always)] + fn recover(tcx: TyCtxt<'tcx>, dep_node: &DepNode) -> Option { + if tcx.fingerprint_style(dep_node.kind) == FingerprintStyle::HirId { + let (local_hash, local_id) = Fingerprint::from(dep_node.hash).split(); + let def_path_hash = DefPathHash::new(tcx.stable_crate_id(LOCAL_CRATE), local_hash); + let def_id = tcx.def_path_hash_to_def_id(def_path_hash)?.expect_local(); + let local_id = local_id + .as_u64() + .try_into() + .unwrap_or_else(|_| panic!("local id should be u32, found {local_id:?}")); + Some(HirId { owner: OwnerId { def_id }, local_id: ItemLocalId::from_u32(local_id) }) + } else { + None + } + } +} + +impl<'tcx> DepNodeKey> for ModDefId { + #[inline(always)] + fn fingerprint_style() -> FingerprintStyle { + FingerprintStyle::DefPathHash + } + + #[inline(always)] + fn to_fingerprint(&self, tcx: TyCtxt<'tcx>) -> Fingerprint { + self.to_def_id().to_fingerprint(tcx) + } + + #[inline(always)] + fn to_debug_str(&self, tcx: TyCtxt<'tcx>) -> String { + self.to_def_id().to_debug_str(tcx) + } + + #[inline(always)] + fn recover(tcx: TyCtxt<'tcx>, dep_node: &DepNode) -> Option { + DefId::recover(tcx, dep_node).map(ModDefId::new_unchecked) + } +} + +impl<'tcx> DepNodeKey> for LocalModDefId { + #[inline(always)] + fn fingerprint_style() -> FingerprintStyle { + FingerprintStyle::DefPathHash + } + + #[inline(always)] + fn to_fingerprint(&self, tcx: TyCtxt<'tcx>) -> Fingerprint { + self.to_def_id().to_fingerprint(tcx) + } + + #[inline(always)] + fn to_debug_str(&self, tcx: TyCtxt<'tcx>) -> String { + self.to_def_id().to_debug_str(tcx) + } + + #[inline(always)] + fn recover(tcx: TyCtxt<'tcx>, dep_node: &DepNode) -> Option { + LocalDefId::recover(tcx, dep_node).map(LocalModDefId::new_unchecked) + } +} diff --git a/compiler/rustc_middle/src/dep_graph/mod.rs b/compiler/rustc_middle/src/dep_graph/mod.rs index f28ba10d52e27..1056fa9b44627 100644 --- a/compiler/rustc_middle/src/dep_graph/mod.rs +++ b/compiler/rustc_middle/src/dep_graph/mod.rs @@ -7,15 +7,17 @@ use crate::ty::{self, TyCtxt}; #[macro_use] mod dep_node; +mod dep_node_key; -pub use dep_node::{DepKind, DepNode, DepNodeExt, dep_kind_from_label, dep_kinds, label_strs}; -pub(crate) use dep_node::{make_compile_codegen_unit, make_compile_mono_item, make_metadata}; pub use rustc_query_system::dep_graph::debug::{DepNodeFilter, EdgeFilter}; pub use rustc_query_system::dep_graph::{ - DepContext, DepGraphQuery, DepNodeIndex, Deps, SerializedDepGraph, SerializedDepNodeIndex, - TaskDepsRef, WorkProduct, WorkProductId, WorkProductMap, hash_result, + DepContext, DepGraphQuery, DepKind, DepNode, DepNodeIndex, Deps, SerializedDepGraph, + SerializedDepNodeIndex, TaskDepsRef, WorkProduct, WorkProductId, WorkProductMap, hash_result, }; +pub use self::dep_node::{DepNodeExt, dep_kind_from_label, dep_kinds, label_strs}; +pub(crate) use self::dep_node::{make_compile_codegen_unit, make_compile_mono_item, make_metadata}; + pub type DepGraph = rustc_query_system::dep_graph::DepGraph; pub type DepKindVTable<'tcx> = rustc_query_system::dep_graph::DepKindVTable>; diff --git a/compiler/rustc_middle/src/lib.rs b/compiler/rustc_middle/src/lib.rs index bb94b4c927ae0..7d1b775cc4bcd 100644 --- a/compiler/rustc_middle/src/lib.rs +++ b/compiler/rustc_middle/src/lib.rs @@ -81,7 +81,6 @@ pub mod thir; pub mod traits; pub mod ty; pub mod util; -mod values; #[macro_use] pub mod query; diff --git a/compiler/rustc_middle/src/query/inner.rs b/compiler/rustc_middle/src/query/inner.rs index bc0b34b67f12f..32fe0737ec12a 100644 --- a/compiler/rustc_middle/src/query/inner.rs +++ b/compiler/rustc_middle/src/query/inner.rs @@ -1,7 +1,7 @@ //! Helper functions that serve as the immediate implementation of //! `tcx.$query(..)` and its variations. -use rustc_query_system::dep_graph::{DepKind, DepNodeParams}; +use rustc_query_system::dep_graph::{DepKind, DepNodeKey}; use rustc_query_system::query::{QueryCache, QueryMode, try_get_cached}; use rustc_span::{DUMMY_SP, ErrorGuaranteed, Span}; @@ -86,7 +86,7 @@ pub(crate) fn query_feed<'tcx, Cache>( value: Cache::Value, ) where Cache: QueryCache, - Cache::Key: DepNodeParams>, + Cache::Key: DepNodeKey>, { let format_value = query_vtable.format_value; diff --git a/compiler/rustc_middle/src/query/mod.rs b/compiler/rustc_middle/src/query/mod.rs index 24a38e70ff6f2..a7707cf48c496 100644 --- a/compiler/rustc_middle/src/query/mod.rs +++ b/compiler/rustc_middle/src/query/mod.rs @@ -13,6 +13,7 @@ mod keys; pub mod on_disk_cache; #[macro_use] pub mod plumbing; +pub mod values; pub fn describe_as_module(def_id: impl Into, tcx: TyCtxt<'_>) -> String { let def_id = def_id.into(); diff --git a/compiler/rustc_middle/src/values.rs b/compiler/rustc_middle/src/query/values.rs similarity index 93% rename from compiler/rustc_middle/src/values.rs rename to compiler/rustc_middle/src/query/values.rs index fd08b5a972c68..0828758cc94ef 100644 --- a/compiler/rustc_middle/src/values.rs +++ b/compiler/rustc_middle/src/query/values.rs @@ -7,7 +7,6 @@ use rustc_errors::codes::*; use rustc_errors::{Applicability, MultiSpan, pluralize, struct_span_code_err}; use rustc_hir as hir; use rustc_hir::def::{DefKind, Res}; -use rustc_query_system::Value; use rustc_query_system::query::{CycleError, report_cycle}; use rustc_span::def_id::LocalDefId; use rustc_span::{ErrorGuaranteed, Span}; @@ -16,7 +15,27 @@ use crate::dep_graph::dep_kinds; use crate::query::plumbing::CyclePlaceholder; use crate::ty::{self, Representability, Ty, TyCtxt}; -impl<'tcx> Value> for Ty<'_> { +pub trait Value<'tcx>: Sized { + fn from_cycle_error(tcx: TyCtxt<'tcx>, cycle_error: &CycleError, guar: ErrorGuaranteed) + -> Self; +} + +impl<'tcx, T> Value<'tcx> for T { + default fn from_cycle_error( + tcx: TyCtxt<'tcx>, + cycle_error: &CycleError, + _guar: ErrorGuaranteed, + ) -> T { + tcx.sess.dcx().abort_if_errors(); + bug!( + "<{} as Value>::from_cycle_error called without errors: {:#?}", + std::any::type_name::(), + cycle_error.cycle, + ); + } +} + +impl<'tcx> Value<'tcx> for Ty<'_> { fn from_cycle_error(tcx: TyCtxt<'tcx>, _: &CycleError, guar: ErrorGuaranteed) -> Self { // SAFETY: This is never called when `Self` is not `Ty<'tcx>`. // FIXME: Represent the above fact in the trait system somehow. @@ -24,13 +43,13 @@ impl<'tcx> Value> for Ty<'_> { } } -impl<'tcx> Value> for Result>, CyclePlaceholder> { +impl<'tcx> Value<'tcx> for Result>, CyclePlaceholder> { fn from_cycle_error(_tcx: TyCtxt<'tcx>, _: &CycleError, guar: ErrorGuaranteed) -> Self { Err(CyclePlaceholder(guar)) } } -impl<'tcx> Value> for ty::SymbolName<'_> { +impl<'tcx> Value<'tcx> for ty::SymbolName<'_> { fn from_cycle_error(tcx: TyCtxt<'tcx>, _: &CycleError, _guar: ErrorGuaranteed) -> Self { // SAFETY: This is never called when `Self` is not `SymbolName<'tcx>`. // FIXME: Represent the above fact in the trait system somehow. @@ -42,7 +61,7 @@ impl<'tcx> Value> for ty::SymbolName<'_> { } } -impl<'tcx> Value> for ty::Binder<'_, ty::FnSig<'_>> { +impl<'tcx> Value<'tcx> for ty::Binder<'_, ty::FnSig<'_>> { fn from_cycle_error( tcx: TyCtxt<'tcx>, cycle_error: &CycleError, @@ -76,7 +95,7 @@ impl<'tcx> Value> for ty::Binder<'_, ty::FnSig<'_>> { } } -impl<'tcx> Value> for Representability { +impl<'tcx> Value<'tcx> for Representability { fn from_cycle_error( tcx: TyCtxt<'tcx>, cycle_error: &CycleError, @@ -112,7 +131,7 @@ impl<'tcx> Value> for Representability { } } -impl<'tcx> Value> for ty::EarlyBinder<'_, Ty<'_>> { +impl<'tcx> Value<'tcx> for ty::EarlyBinder<'_, Ty<'_>> { fn from_cycle_error( tcx: TyCtxt<'tcx>, cycle_error: &CycleError, @@ -122,7 +141,7 @@ impl<'tcx> Value> for ty::EarlyBinder<'_, Ty<'_>> { } } -impl<'tcx> Value> for ty::EarlyBinder<'_, ty::Binder<'_, ty::FnSig<'_>>> { +impl<'tcx> Value<'tcx> for ty::EarlyBinder<'_, ty::Binder<'_, ty::FnSig<'_>>> { fn from_cycle_error( tcx: TyCtxt<'tcx>, cycle_error: &CycleError, @@ -132,7 +151,7 @@ impl<'tcx> Value> for ty::EarlyBinder<'_, ty::Binder<'_, ty::FnSig< } } -impl<'tcx> Value> for &[ty::Variance] { +impl<'tcx> Value<'tcx> for &[ty::Variance] { fn from_cycle_error( tcx: TyCtxt<'tcx>, cycle_error: &CycleError, @@ -180,7 +199,7 @@ fn search_for_cycle_permutation( otherwise() } -impl<'tcx, T> Value> for Result> { +impl<'tcx, T> Value<'tcx> for Result> { fn from_cycle_error( tcx: TyCtxt<'tcx>, cycle_error: &CycleError, @@ -273,7 +292,7 @@ impl<'tcx, T> Value> for Result> // item_and_field_ids should form a cycle where each field contains the // type in the next element in the list -pub fn recursive_type_error( +fn recursive_type_error( tcx: TyCtxt<'_>, mut item_and_field_ids: Vec<(LocalDefId, LocalDefId)>, representable_ids: &FxHashSet, diff --git a/compiler/rustc_mir_transform/Cargo.toml b/compiler/rustc_mir_transform/Cargo.toml index 404531eb3c91f..395127edd1e0a 100644 --- a/compiler/rustc_mir_transform/Cargo.toml +++ b/compiler/rustc_mir_transform/Cargo.toml @@ -13,7 +13,6 @@ rustc_ast = { path = "../rustc_ast" } rustc_const_eval = { path = "../rustc_const_eval" } rustc_data_structures = { path = "../rustc_data_structures" } rustc_errors = { path = "../rustc_errors" } -rustc_fluent_macro = { path = "../rustc_fluent_macro" } rustc_hir = { path = "../rustc_hir" } rustc_index = { path = "../rustc_index" } rustc_infer = { path = "../rustc_infer" } diff --git a/compiler/rustc_mir_transform/messages.ftl b/compiler/rustc_mir_transform/messages.ftl deleted file mode 100644 index 7924c015200f1..0000000000000 --- a/compiler/rustc_mir_transform/messages.ftl +++ /dev/null @@ -1,114 +0,0 @@ -mir_transform_arithmetic_overflow = this arithmetic operation will overflow - -mir_transform_asm_unwind_call = call to inline assembly that may unwind - -mir_transform_const_defined_here = `const` item defined here - -mir_transform_const_modify = 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 - -mir_transform_const_mut_borrow = taking a mutable reference to a `const` item - .note = each usage of a `const` item creates a new temporary - .note2 = the mutable reference will refer to this temporary, not the original `const` item - .note3 = mutable reference created due to call to this method - -mir_transform_ffi_unwind_call = call to {$foreign -> - [true] foreign function - *[false] function pointer - } with FFI-unwind ABI - -mir_transform_fn_item_ref = taking a reference to a function item does not give a function pointer - .suggestion = cast `{$ident}` to obtain a function pointer - -mir_transform_force_inline = - `{$callee}` could not be inlined into `{$caller}` but is required to be inlined - .call = ...`{$callee}` called here - .attr = inlining due to this annotation - .caller = within `{$caller}`... - .callee = `{$callee}` defined here - .note = could not be inlined due to: {$reason} - -mir_transform_force_inline_attr = - `{$callee}` is incompatible with `#[rustc_force_inline]` - .attr = annotation here - .callee = `{$callee}` defined here - .note = incompatible due to: {$reason} - -mir_transform_force_inline_justification = - `{$callee}` is required to be inlined to: {$sym} - -mir_transform_maybe_string_interpolation = you might have meant to use string interpolation in this string literal - -mir_transform_must_not_suspend = {$pre}`{$def_path}`{$post} held across a suspend point, but should not be - .label = the value is held across this suspend point - .note = {$reason} - .help = consider using a block (`{"{ ... }"}`) to shrink the value's scope, ending before the suspend point -mir_transform_operation_will_panic = this operation will panic at runtime - -mir_transform_string_interpolation_only_works = string interpolation only works in `format!` invocations - -mir_transform_tail_expr_drop_order = relative drop order changing in Rust 2024 - .temporaries = in Rust 2024, this temporary value will be dropped first - .observers = in Rust 2024, this local variable or temporary value will be dropped second - .note_dtors = - dropping the temporary value runs this custom `Drop` impl, which we could not prove to be side-effect free - .note_observer_dtors = - dropping the local runs this custom `Drop` impl, which we could not prove to be side-effect free - .drop_location = - now the temporary value is dropped here, before the local variables in the block or statement - .note_epilogue = most of the time, changing drop order is harmless; inspect the `impl Drop`s for side effects like releasing locks or sending messages - .label_local_epilogue = {$is_dropped_first_edition_2024 -> - [true] up until Edition 2021 `{$name}` is dropped last but will be dropped earlier in Edition 2024 - *[false] `{$name}` will be dropped later as of Edition 2024 - } - -mir_transform_tail_expr_dtor = {$dtor_kind -> - [dyn] `{$name}` may invoke a custom destructor because it contains a trait object - *[concrete] `{$name}` invokes this custom destructor - } - -mir_transform_tail_expr_local = {$is_generated_name -> - [true] this value will be stored in a temporary; let us call it `{$name}` - *[false] `{$name}` calls a custom destructor - } - -mir_transform_unaligned_packed_ref = reference to field of packed {$ty_descr} is unaligned - .note = this {$ty_descr} is {$align -> - [one] {""} - *[other] {"at most "} - }{$align}-byte aligned, but the type of this field may require higher alignment - .note_ub = 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) - -mir_transform_unconditional_recursion = function cannot return without recursing - .label = cannot return without recursing - .help = a `loop` may express intention better if this is on purpose - -mir_transform_unconditional_recursion_call_site_label = recursive call site - -mir_transform_unknown_pass_name = MIR pass `{$name}` is unknown and will be ignored - -mir_transform_unused_assign = value assigned to `{$name}` is never read - .help = maybe it is overwritten before being read? - -mir_transform_unused_assign_passed = value passed to `{$name}` is never read - .help = maybe it is overwritten before being read? - -mir_transform_unused_assign_suggestion = - you might have meant to mutate the pointed at value being passed in, instead of changing the reference in the local binding - -mir_transform_unused_capture_maybe_capture_ref = value captured by `{$name}` is never read - .help = did you mean to capture by reference instead? - -mir_transform_unused_var_assigned_only = variable `{$name}` is assigned to, but never used - .note = consider using `_{$name}` instead - -mir_transform_unused_var_underscore = if this is intentional, prefix it with an underscore - -mir_transform_unused_variable = unused variable: `{$name}` - -mir_transform_unused_variable_args_in_macro = `{$name}` is captured in macro and introduced a unused variable - -mir_transform_unused_variable_try_ignore = try ignoring the field - -mir_transform_unused_variable_typo = you might have meant to pattern match on the similarly named {$kind} `{$item_name}` diff --git a/compiler/rustc_mir_transform/src/errors.rs b/compiler/rustc_mir_transform/src/errors.rs index d4c58f7fe05d9..7407a0e022d3a 100644 --- a/compiler/rustc_mir_transform/src/errors.rs +++ b/compiler/rustc_mir_transform/src/errors.rs @@ -1,5 +1,7 @@ use rustc_errors::codes::*; -use rustc_errors::{Applicability, Diag, EmissionGuarantee, LintDiagnostic, Subdiagnostic}; +use rustc_errors::{ + Applicability, Diag, EmissionGuarantee, LintDiagnostic, Subdiagnostic, inline_fluent, +}; use rustc_macros::{Diagnostic, LintDiagnostic, Subdiagnostic}; use rustc_middle::mir::AssertKind; use rustc_middle::query::Key; @@ -8,8 +10,6 @@ use rustc_session::lint::{self, Lint}; use rustc_span::def_id::DefId; use rustc_span::{Ident, Span, Symbol}; -use crate::fluent_generated as fluent; - /// Emit diagnostic for calls to `#[inline(always)]`-annotated functions with a /// `#[target_feature]` attribute where the caller enables a different set of target features. pub(crate) fn emit_inline_always_target_feature_diagnostic<'a, 'tcx>( @@ -51,22 +51,22 @@ pub(crate) fn emit_inline_always_target_feature_diagnostic<'a, 'tcx>( } #[derive(LintDiagnostic)] -#[diag(mir_transform_unconditional_recursion)] -#[help] +#[diag("function cannot return without recursing")] +#[help("a `loop` may express intention better if this is on purpose")] pub(crate) struct UnconditionalRecursion { - #[label] + #[label("cannot return without recursing")] pub(crate) span: Span, - #[label(mir_transform_unconditional_recursion_call_site_label)] + #[label("recursive call site")] pub(crate) call_sites: Vec, } #[derive(Diagnostic)] -#[diag(mir_transform_force_inline_attr)] -#[note] +#[diag("`{$callee}` is incompatible with `#[rustc_force_inline]`")] +#[note("incompatible due to: {$reason}")] pub(crate) struct InvalidForceInline { #[primary_span] pub attr_span: Span, - #[label(mir_transform_callee)] + #[label("`{$callee}` defined here")] pub callee_span: Span, pub callee: String, pub reason: &'static str, @@ -74,28 +74,39 @@ pub(crate) struct InvalidForceInline { #[derive(LintDiagnostic)] pub(crate) enum ConstMutate { - #[diag(mir_transform_const_modify)] - #[note] + #[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(mir_transform_const_defined_here)] + #[note("`const` item defined here")] konst: Span, }, - #[diag(mir_transform_const_mut_borrow)] - #[note] - #[note(mir_transform_note2)] + #[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(mir_transform_note3)] + #[note("mutable reference created due to call to this method")] method_call: Option, - #[note(mir_transform_const_defined_here)] + #[note("`const` item defined here")] konst: Span, }, } #[derive(Diagnostic)] -#[diag(mir_transform_unaligned_packed_ref, code = E0793)] -#[note] -#[note(mir_transform_note_ub)] -#[help] +#[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, @@ -104,7 +115,7 @@ pub(crate) struct UnalignedPackedRef { } #[derive(Diagnostic)] -#[diag(mir_transform_unknown_pass_name)] +#[diag("MIR pass `{$name}` is unknown and will be ignored")] pub(crate) struct UnknownPassName<'a> { pub(crate) name: &'a str, } @@ -123,8 +134,12 @@ pub(crate) enum AssertLintKind { impl<'a, P: std::fmt::Debug> LintDiagnostic<'a, ()> for AssertLint

{ fn decorate_lint<'b>(self, diag: &'b mut Diag<'a, ()>) { diag.primary_message(match self.lint_kind { - AssertLintKind::ArithmeticOverflow => fluent::mir_transform_arithmetic_overflow, - AssertLintKind::UnconditionalPanic => fluent::mir_transform_operation_will_panic, + AssertLintKind::ArithmeticOverflow => { + inline_fluent!("this arithmetic operation will overflow") + } + AssertLintKind::UnconditionalPanic => { + inline_fluent!("this operation will panic at runtime") + } }); let label = self.assert_kind.diagnostic_message(); self.assert_kind.add_args(&mut |name, value| { @@ -144,39 +159,53 @@ impl AssertLintKind { } #[derive(LintDiagnostic)] -#[diag(mir_transform_asm_unwind_call)] +#[diag("call to inline assembly that may unwind")] pub(crate) struct AsmUnwindCall { - #[label(mir_transform_asm_unwind_call)] + #[label("call to inline assembly that may unwind")] pub span: Span, } #[derive(LintDiagnostic)] -#[diag(mir_transform_ffi_unwind_call)] +#[diag( + "call to {$foreign -> + [true] foreign function + *[false] function pointer + } with FFI-unwind ABI" +)] pub(crate) struct FfiUnwindCall { - #[label(mir_transform_ffi_unwind_call)] + #[label( + "call to {$foreign -> + [true] foreign function + *[false] function pointer + } with FFI-unwind ABI" + )] pub span: Span, pub foreign: bool, } #[derive(LintDiagnostic)] -#[diag(mir_transform_fn_item_ref)] +#[diag("taking a reference to a function item does not give a function pointer")] pub(crate) struct FnItemRef { - #[suggestion(code = "{sugg}", applicability = "unspecified")] + #[suggestion( + "cast `{$ident}` to obtain a function pointer", + code = "{sugg}", + applicability = "unspecified" + )] pub span: Span, pub sugg: String, pub ident: Ident, } #[derive(LintDiagnostic)] -#[diag(mir_transform_unused_capture_maybe_capture_ref)] -#[help] +#[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(LintDiagnostic)] -#[diag(mir_transform_unused_var_assigned_only)] -#[note] +#[diag("variable `{$name}` is assigned to, but never used")] +#[note("consider using `_{$name}` instead")] pub(crate) struct UnusedVarAssignedOnly { pub name: Symbol, #[subdiagnostic] @@ -184,17 +213,20 @@ pub(crate) struct UnusedVarAssignedOnly { } #[derive(LintDiagnostic)] -#[diag(mir_transform_unused_assign)] +#[diag("value assigned to `{$name}` is never read")] pub(crate) struct UnusedAssign { pub name: Symbol, #[subdiagnostic] pub suggestion: Option, - #[help] + #[help("maybe it is overwritten before being read?")] pub help: bool, } #[derive(Subdiagnostic)] -#[multipart_suggestion(mir_transform_unused_assign_suggestion, applicability = "maybe-incorrect")] +#[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 ")] @@ -208,14 +240,14 @@ pub(crate) struct UnusedAssignSuggestion { } #[derive(LintDiagnostic)] -#[diag(mir_transform_unused_assign_passed)] -#[help] +#[diag("value passed to `{$name}` is never read")] +#[help("maybe it is overwritten before being read?")] pub(crate) struct UnusedAssignPassed { pub name: Symbol, } #[derive(LintDiagnostic)] -#[diag(mir_transform_unused_variable)] +#[diag("unused variable: `{$name}`")] pub(crate) struct UnusedVariable { pub name: Symbol, #[subdiagnostic] @@ -226,10 +258,7 @@ pub(crate) struct UnusedVariable { #[derive(Subdiagnostic)] pub(crate) enum UnusedVariableSugg { - #[multipart_suggestion( - mir_transform_unused_variable_try_ignore, - applicability = "machine-applicable" - )] + #[multipart_suggestion("try ignoring the field", applicability = "machine-applicable")] TryIgnore { #[suggestion_part(code = "{name}: _")] shorthands: Vec, @@ -239,7 +268,7 @@ pub(crate) enum UnusedVariableSugg { }, #[multipart_suggestion( - mir_transform_unused_var_underscore, + "if this is intentional, prefix it with an underscore", applicability = "machine-applicable" )] TryPrefix { @@ -250,7 +279,7 @@ pub(crate) enum UnusedVariableSugg { typo: Option, }, - #[help(mir_transform_unused_variable_args_in_macro)] + #[help("`{$name}` is captured in macro and introduced a unused variable")] NoSugg { #[primary_span] span: Span, @@ -266,10 +295,12 @@ impl Subdiagnostic for UnusedVariableStringInterp { fn add_to_diag(self, diag: &mut Diag<'_, G>) { diag.span_label( self.lit, - crate::fluent_generated::mir_transform_maybe_string_interpolation, + inline_fluent!( + "you might have meant to use string interpolation in this string literal" + ), ); diag.multipart_suggestion( - crate::fluent_generated::mir_transform_string_interpolation_only_works, + inline_fluent!("string interpolation only works in `format!` invocations"), vec![ (self.lit.shrink_to_lo(), String::from("format!(")), (self.lit.shrink_to_hi(), String::from(")")), @@ -281,7 +312,7 @@ impl Subdiagnostic for UnusedVariableStringInterp { #[derive(Subdiagnostic)] #[multipart_suggestion( - mir_transform_unused_variable_typo, + "you might have meant to pattern match on the similarly named {$kind} `{$item_name}`", style = "verbose", applicability = "maybe-incorrect" )] @@ -306,12 +337,17 @@ pub(crate) struct MustNotSupend<'a, 'tcx> { // Needed for def_path_str impl<'a> LintDiagnostic<'a, ()> for MustNotSupend<'_, '_> { fn decorate_lint<'b>(self, diag: &'b mut rustc_errors::Diag<'a, ()>) { - diag.primary_message(fluent::mir_transform_must_not_suspend); - diag.span_label(self.yield_sp, fluent::_subdiag::label); + diag.primary_message(inline_fluent!( + "{$pre}`{$def_path}`{$post} held across a suspend point, but should not be" + )); + diag.span_label( + self.yield_sp, + inline_fluent!("the value is held across this suspend point"), + ); if let Some(reason) = self.reason { diag.subdiagnostic(reason); } - diag.span_help(self.src_sp, fluent::_subdiag::help); + diag.span_help(self.src_sp, inline_fluent!("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); @@ -319,7 +355,7 @@ impl<'a> LintDiagnostic<'a, ()> for MustNotSupend<'_, '_> { } #[derive(Subdiagnostic)] -#[note(mir_transform_note)] +#[note("{$reason}")] pub(crate) struct MustNotSuspendReason { #[primary_span] pub span: Span, @@ -327,17 +363,17 @@ pub(crate) struct MustNotSuspendReason { } #[derive(Diagnostic)] -#[diag(mir_transform_force_inline)] -#[note] +#[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(mir_transform_caller)] + #[label("within `{$caller}`...")] pub caller_span: Span, - #[label(mir_transform_callee)] + #[label("`{$callee}` defined here")] pub callee_span: Span, - #[label(mir_transform_attr)] + #[label("annotation here")] pub attr_span: Span, #[primary_span] - #[label(mir_transform_call)] + #[label("...`{$callee}` called here")] pub call_span: Span, pub callee: String, pub caller: String, @@ -347,7 +383,7 @@ pub(crate) struct ForceInlineFailure { } #[derive(Subdiagnostic)] -#[note(mir_transform_force_inline_justification)] +#[note("`{$callee}` is required to be inlined to: {$sym}")] pub(crate) struct ForceInlineJustification { pub sym: Symbol, } diff --git a/compiler/rustc_mir_transform/src/lib.rs b/compiler/rustc_mir_transform/src/lib.rs index 0e6a1a414e45f..0610d90202a1b 100644 --- a/compiler/rustc_mir_transform/src/lib.rs +++ b/compiler/rustc_mir_transform/src/lib.rs @@ -213,8 +213,6 @@ declare_passes! { mod validate : Validator; } -rustc_fluent_macro::fluent_messages! { "../messages.ftl" } - pub fn provide(providers: &mut Providers) { coverage::query::provide(providers); ffi_unwind_calls::provide(&mut providers.queries); diff --git a/compiler/rustc_mir_transform/src/lint_tail_expr_drop_order.rs b/compiler/rustc_mir_transform/src/lint_tail_expr_drop_order.rs index 61c9bbe31239e..789398c588808 100644 --- a/compiler/rustc_mir_transform/src/lint_tail_expr_drop_order.rs +++ b/compiler/rustc_mir_transform/src/lint_tail_expr_drop_order.rs @@ -5,7 +5,7 @@ use std::rc::Rc; use itertools::Itertools as _; use rustc_data_structures::fx::{FxHashMap, FxHashSet, FxIndexMap}; use rustc_data_structures::unord::{UnordMap, UnordSet}; -use rustc_errors::Subdiagnostic; +use rustc_errors::{Subdiagnostic, inline_fluent}; use rustc_hir::CRATE_HIR_ID; use rustc_hir::def_id::LocalDefId; use rustc_index::bit_set::MixedBitSet; @@ -499,13 +499,17 @@ fn assign_observables_names( } #[derive(LintDiagnostic)] -#[diag(mir_transform_tail_expr_drop_order)] +#[diag("relative drop order changing in Rust 2024")] struct TailExprDropOrderLint<'a> { #[subdiagnostic] local_labels: Vec>, - #[label(mir_transform_drop_location)] + #[label( + "now the temporary value is dropped here, before the local variables in the block or statement" + )] drop_span: Option, - #[note(mir_transform_note_epilogue)] + #[note( + "most of the time, changing drop order is harmless; inspect the `impl Drop`s for side effects like releasing locks or sending messages" + )] _epilogue: (), } @@ -527,19 +531,32 @@ impl Subdiagnostic for LocalLabel<'_> { diag.arg("is_generated_name", self.is_generated_name); diag.remove_arg("is_dropped_first_edition_2024"); diag.arg("is_dropped_first_edition_2024", self.is_dropped_first_edition_2024); - let msg = diag.eagerly_translate(crate::fluent_generated::mir_transform_tail_expr_local); + let msg = diag.eagerly_translate(inline_fluent!( + "{$is_generated_name -> + [true] this value will be stored in a temporary; let us call it `{$name}` + *[false] `{$name}` calls a custom destructor + }" + )); diag.span_label(self.span, msg); for dtor in self.destructors { dtor.add_to_diag(diag); } let msg = - diag.eagerly_translate(crate::fluent_generated::mir_transform_label_local_epilogue); + diag.eagerly_translate(inline_fluent!("{$is_dropped_first_edition_2024 -> + [true] up until Edition 2021 `{$name}` is dropped last but will be dropped earlier in Edition 2024 + *[false] `{$name}` will be dropped later as of Edition 2024 + }")); diag.span_label(self.span, msg); } } #[derive(Subdiagnostic)] -#[note(mir_transform_tail_expr_dtor)] +#[note( + "{$dtor_kind -> + [dyn] `{$name}` may invoke a custom destructor because it contains a trait object + *[concrete] `{$name}` invokes this custom destructor + }" +)] struct DestructorLabel<'a> { #[primary_span] span: Span, diff --git a/compiler/rustc_passes/messages.ftl b/compiler/rustc_passes/messages.ftl index ab89af2267934..fae0052ab7a43 100644 --- a/compiler/rustc_passes/messages.ftl +++ b/compiler/rustc_passes/messages.ftl @@ -441,8 +441,6 @@ passes_rustc_allow_const_fn_unstable = passes_rustc_const_stable_indirect_pairing = `const_stable_indirect` attribute does not make sense on `rustc_const_stable` function, its behavior is already implied -passes_rustc_dirty_clean = - attribute requires -Z query-dep-graph to be enabled passes_rustc_force_inline_coro = attribute cannot be applied to a `async`, `gen` or `async gen` function diff --git a/compiler/rustc_passes/src/check_attr.rs b/compiler/rustc_passes/src/check_attr.rs index 4784456a59d9c..0d64e30d9c79e 100644 --- a/compiler/rustc_passes/src/check_attr.rs +++ b/compiler/rustc_passes/src/check_attr.rs @@ -284,6 +284,7 @@ impl<'tcx> CheckAttrVisitor<'tcx> { | AttributeKind::Pointee(..) | AttributeKind::ProfilerRuntime | AttributeKind::RecursionLimit { .. } + | AttributeKind::ReexportTestHarnessMain(..) // handled below this loop and elsewhere | AttributeKind::Repr { .. } | AttributeKind::RustcAllocator @@ -292,6 +293,7 @@ impl<'tcx> CheckAttrVisitor<'tcx> { | AttributeKind::RustcAsPtr(..) | AttributeKind::RustcBodyStability { .. } | AttributeKind::RustcBuiltinMacro { .. } + | AttributeKind::RustcClean(..) | AttributeKind::RustcCoherenceIsCore(..) | AttributeKind::RustcCoinductive(..) | AttributeKind::RustcConfusables { .. } @@ -307,6 +309,7 @@ impl<'tcx> CheckAttrVisitor<'tcx> { | AttributeKind::RustcDynIncompatibleTrait(..) | AttributeKind::RustcHasIncoherentInherentImpls | AttributeKind::RustcHiddenTypeOfOpaques + | AttributeKind::RustcIfThisChanged(..) | AttributeKind::RustcLayout(..) | AttributeKind::RustcLayoutScalarValidRangeEnd(..) | AttributeKind::RustcLayoutScalarValidRangeStart(..) @@ -335,6 +338,7 @@ impl<'tcx> CheckAttrVisitor<'tcx> { | AttributeKind::RustcSkipDuringMethodDispatch { .. } | AttributeKind::RustcSpecializationTrait(..) | AttributeKind::RustcStdInternalSymbol (..) + | AttributeKind::RustcThenThisWouldNeed(..) | AttributeKind::RustcUnsafeSpecializationMarker(..) | AttributeKind::RustcVariance | AttributeKind::RustcVarianceOfOpaques @@ -356,10 +360,6 @@ impl<'tcx> CheckAttrVisitor<'tcx> { [sym::diagnostic, sym::on_const, ..] => { self.check_diagnostic_on_const(attr.span(), hir_id, target, item) } - [sym::rustc_clean, ..] - | [sym::rustc_dirty, ..] - | [sym::rustc_if_this_changed, ..] - | [sym::rustc_then_this_would_need, ..] => self.check_rustc_dirty_clean(attr), [sym::autodiff_forward, ..] | [sym::autodiff_reverse, ..] => { self.check_autodiff(hir_id, attr, span, target) } @@ -414,8 +414,7 @@ impl<'tcx> CheckAttrVisitor<'tcx> { | sym::feature | sym::register_tool | sym::rustc_no_implicit_bounds - | sym::test_runner - | sym::reexport_test_harness_main, + | sym::test_runner, .. ] => {} [name, rest@..] => { @@ -1260,14 +1259,6 @@ impl<'tcx> CheckAttrVisitor<'tcx> { } } - /// Checks that the dep-graph debugging attributes are only present when the query-dep-graph - /// option is passed to the compiler. - fn check_rustc_dirty_clean(&self, attr: &Attribute) { - if !self.tcx.sess.opts.unstable_opts.query_dep_graph { - self.dcx().emit_err(errors::RustcDirtyClean { span: attr.span() }); - } - } - /// Checks if the `#[repr]` attributes on `item` are valid. fn check_repr( &self, diff --git a/compiler/rustc_passes/src/errors.rs b/compiler/rustc_passes/src/errors.rs index 29688dd4d5377..d0fa1c4f0e037 100644 --- a/compiler/rustc_passes/src/errors.rs +++ b/compiler/rustc_passes/src/errors.rs @@ -217,13 +217,6 @@ pub(crate) struct RustcLegacyConstGenericsIndexExceed { pub arg_count: usize, } -#[derive(Diagnostic)] -#[diag(passes_rustc_dirty_clean)] -pub(crate) struct RustcDirtyClean { - #[primary_span] - pub span: Span, -} - #[derive(Diagnostic)] #[diag(passes_repr_conflicting, code = E0566)] pub(crate) struct ReprConflicting { diff --git a/compiler/rustc_query_impl/Cargo.toml b/compiler/rustc_query_impl/Cargo.toml index 257785b10c8bc..d611629671a0a 100644 --- a/compiler/rustc_query_impl/Cargo.toml +++ b/compiler/rustc_query_impl/Cargo.toml @@ -7,9 +7,11 @@ edition = "2024" # tidy-alphabetical-start measureme = "12.0.1" rustc_data_structures = { path = "../rustc_data_structures" } +rustc_errors = { path = "../rustc_errors" } rustc_hashes = { path = "../rustc_hashes" } rustc_hir = { path = "../rustc_hir" } rustc_index = { path = "../rustc_index" } +rustc_macros = { path = "../rustc_macros" } rustc_middle = { path = "../rustc_middle" } rustc_query_system = { path = "../rustc_query_system" } rustc_serialize = { path = "../rustc_serialize" } diff --git a/compiler/rustc_query_impl/src/error.rs b/compiler/rustc_query_impl/src/error.rs new file mode 100644 index 0000000000000..b109172d8e495 --- /dev/null +++ b/compiler/rustc_query_impl/src/error.rs @@ -0,0 +1,24 @@ +use rustc_hir::limit::Limit; +use rustc_macros::{Diagnostic, Subdiagnostic}; +use rustc_span::{Span, Symbol}; + +#[derive(Diagnostic)] +#[help( + "consider increasing the recursion limit by adding a `#![recursion_limit = \"{$suggested_limit}\"]` attribute to your crate (`{$crate_name}`)" +)] +#[diag("queries overflow the depth limit!")] +pub(crate) struct QueryOverflow { + #[primary_span] + pub span: Span, + #[subdiagnostic] + pub note: QueryOverflowNote, + pub suggested_limit: Limit, + pub crate_name: Symbol, +} + +#[derive(Subdiagnostic)] +#[note("query depth increased by {$depth} when {$desc}")] +pub(crate) struct QueryOverflowNote { + pub desc: String, + pub depth: usize, +} diff --git a/compiler/rustc_query_impl/src/lib.rs b/compiler/rustc_query_impl/src/lib.rs index baa37111c8070..cb5010861e5f8 100644 --- a/compiler/rustc_query_impl/src/lib.rs +++ b/compiler/rustc_query_impl/src/lib.rs @@ -19,8 +19,8 @@ use rustc_middle::queries::{ use rustc_middle::query::AsLocalKey; use rustc_middle::query::on_disk_cache::{CacheEncoder, EncodedDepNodeIndex, OnDiskCache}; use rustc_middle::query::plumbing::{QuerySystem, QuerySystemFns, QueryVTable}; +use rustc_middle::query::values::Value; use rustc_middle::ty::TyCtxt; -use rustc_query_system::Value; use rustc_query_system::dep_graph::SerializedDepNodeIndex; use rustc_query_system::ich::StableHashingContext; use rustc_query_system::query::{ @@ -39,6 +39,8 @@ pub use crate::plumbing::{QueryCtxt, query_key_hash_verify_all}; mod profiling_support; pub use self::profiling_support::alloc_self_profile_query_strings; +mod error; + #[derive(ConstParamTy)] // Allow this struct to be used for const-generic values. #[derive(Clone, Copy, Debug, PartialEq, Eq)] struct QueryFlags { diff --git a/compiler/rustc_query_impl/src/plumbing.rs b/compiler/rustc_query_impl/src/plumbing.rs index b074a9ca11b02..304d0169d1123 100644 --- a/compiler/rustc_query_impl/src/plumbing.rs +++ b/compiler/rustc_query_impl/src/plumbing.rs @@ -24,17 +24,17 @@ use rustc_middle::ty::codec::TyEncoder; use rustc_middle::ty::print::with_reduced_queries; use rustc_middle::ty::tls::{self, ImplicitCtxt}; use rustc_middle::ty::{self, TyCtxt}; -use rustc_query_system::dep_graph::{DepNodeParams, FingerprintStyle, HasDepContext}; +use rustc_query_system::dep_graph::{DepNodeKey, FingerprintStyle, HasDepContext}; use rustc_query_system::ich::StableHashingContext; use rustc_query_system::query::{ QueryCache, QueryContext, QueryDispatcher, QueryJobId, QueryMap, QuerySideEffect, QueryStackDeferred, QueryStackFrame, QueryStackFrameExtra, force_query, }; -use rustc_query_system::{QueryOverflow, QueryOverflowNote}; use rustc_serialize::{Decodable, Encodable}; use rustc_span::def_id::LOCAL_CRATE; use crate::QueryDispatcherUnerased; +use crate::error::{QueryOverflow, QueryOverflowNote}; /// Implements [`QueryContext`] for use by [`rustc_query_system`], since that /// crate does not have direct access to [`TyCtxt`]. diff --git a/compiler/rustc_query_system/src/cache.rs b/compiler/rustc_query_system/src/cache.rs index 1b8332ad9e015..4217d0a49b91d 100644 --- a/compiler/rustc_query_system/src/cache.rs +++ b/compiler/rustc_query_system/src/cache.rs @@ -23,13 +23,6 @@ impl Default for Cache { } } -impl Cache { - /// Actually frees the underlying memory in contrast to what stdlib containers do on `clear` - pub fn clear(&self) { - *self.hashmap.borrow_mut() = Default::default(); - } -} - impl Cache { pub fn get(&self, key: &Key, tcx: Tcx) -> Option { Some(self.hashmap.borrow().get(key)?.get(tcx)) diff --git a/compiler/rustc_query_system/src/dep_graph/dep_node.rs b/compiler/rustc_query_system/src/dep_graph/dep_node.rs index b9d35bc5a9379..5df50b2864b24 100644 --- a/compiler/rustc_query_system/src/dep_graph/dep_node.rs +++ b/compiler/rustc_query_system/src/dep_graph/dep_node.rs @@ -124,7 +124,7 @@ impl DepNode { pub fn construct(tcx: Tcx, kind: DepKind, arg: &Key) -> DepNode where Tcx: super::DepContext, - Key: DepNodeParams, + Key: DepNodeKey, { let hash = arg.to_fingerprint(tcx); let dep_node = DepNode { kind, hash: hash.into() }; @@ -167,16 +167,13 @@ impl fmt::Debug for DepNode { } } -pub trait DepNodeParams: fmt::Debug + Sized { +/// Trait for query keys as seen by dependency-node tracking. +pub trait DepNodeKey: fmt::Debug + Sized { fn fingerprint_style() -> FingerprintStyle; - /// This method turns the parameters of a DepNodeConstructor into an opaque - /// Fingerprint to be used in DepNode. - /// Not all DepNodeParams support being turned into a Fingerprint (they - /// don't need to if the corresponding DepNode is anonymous). - fn to_fingerprint(&self, _: Tcx) -> Fingerprint { - panic!("Not implemented. Accidentally called on anonymous node?") - } + /// This method turns a query key into an opaque `Fingerprint` to be used + /// in `DepNode`. + fn to_fingerprint(&self, _: Tcx) -> Fingerprint; fn to_debug_str(&self, tcx: Tcx) -> String; @@ -189,7 +186,8 @@ pub trait DepNodeParams: fmt::Debug + Sized { fn recover(tcx: Tcx, dep_node: &DepNode) -> Option; } -impl DepNodeParams for T +// Blanket impl of `DepNodeKey`, which is specialized by other impls elsewhere. +impl DepNodeKey for T where T: for<'a> HashStable> + fmt::Debug, { @@ -239,7 +237,7 @@ pub struct DepKindVTable { /// Indicates whether and how the query key can be recovered from its hashed fingerprint. /// - /// The [`DepNodeParams`] trait determines the fingerprint style for each key type. + /// The [`DepNodeKey`] trait determines the fingerprint style for each key type. pub fingerprint_style: FingerprintStyle, /// The red/green evaluation system will try to mark a specific DepNode in the diff --git a/compiler/rustc_query_system/src/dep_graph/mod.rs b/compiler/rustc_query_system/src/dep_graph/mod.rs index c3ac1c7bc2d5a..f2cb01d5e9b42 100644 --- a/compiler/rustc_query_system/src/dep_graph/mod.rs +++ b/compiler/rustc_query_system/src/dep_graph/mod.rs @@ -7,7 +7,7 @@ mod serialized; use std::panic; -pub use dep_node::{DepKind, DepKindVTable, DepNode, DepNodeParams, WorkProductId}; +pub use dep_node::{DepKind, DepKindVTable, DepNode, DepNodeKey, WorkProductId}; pub(crate) use graph::DepGraphData; pub use graph::{DepGraph, DepNodeIndex, TaskDepsRef, WorkProduct, WorkProductMap, hash_result}; pub use query::DepGraphQuery; diff --git a/compiler/rustc_query_system/src/error.rs b/compiler/rustc_query_system/src/error.rs index 55f2feba0d861..adce85bf31be2 100644 --- a/compiler/rustc_query_system/src/error.rs +++ b/compiler/rustc_query_system/src/error.rs @@ -1,7 +1,6 @@ use rustc_errors::codes::*; -use rustc_hir::limit::Limit; use rustc_macros::{Diagnostic, Subdiagnostic}; -use rustc_span::{Span, Symbol}; +use rustc_span::Span; #[derive(Subdiagnostic)] #[note("...which requires {$desc}...")] @@ -75,24 +74,3 @@ pub(crate) struct IncrementCompilation { pub run_cmd: String, pub dep_node: String, } - -#[derive(Diagnostic)] -#[help( - "consider increasing the recursion limit by adding a `#![recursion_limit = \"{$suggested_limit}\"]` attribute to your crate (`{$crate_name}`)" -)] -#[diag("queries overflow the depth limit!")] -pub struct QueryOverflow { - #[primary_span] - pub span: Span, - #[subdiagnostic] - pub note: QueryOverflowNote, - pub suggested_limit: Limit, - pub crate_name: Symbol, -} - -#[derive(Subdiagnostic)] -#[note("query depth increased by {$depth} when {$desc}")] -pub struct QueryOverflowNote { - pub desc: String, - pub depth: usize, -} diff --git a/compiler/rustc_query_system/src/ich/mod.rs b/compiler/rustc_query_system/src/ich/mod.rs index 25778add60a98..72a7f3b8f970a 100644 --- a/compiler/rustc_query_system/src/ich/mod.rs +++ b/compiler/rustc_query_system/src/ich/mod.rs @@ -11,7 +11,6 @@ pub const IGNORED_ATTRIBUTES: &[Symbol] = &[ sym::cfg_trace, // FIXME should this really be ignored? sym::rustc_if_this_changed, sym::rustc_then_this_would_need, - sym::rustc_dirty, sym::rustc_clean, sym::rustc_partition_reused, sym::rustc_partition_codegened, diff --git a/compiler/rustc_query_system/src/lib.rs b/compiler/rustc_query_system/src/lib.rs index d1907a8c582d8..61edf397886b1 100644 --- a/compiler/rustc_query_system/src/lib.rs +++ b/compiler/rustc_query_system/src/lib.rs @@ -10,7 +10,3 @@ pub mod dep_graph; mod error; pub mod ich; pub mod query; -mod values; - -pub use error::{QueryOverflow, QueryOverflowNote}; -pub use values::Value; diff --git a/compiler/rustc_query_system/src/query/dispatcher.rs b/compiler/rustc_query_system/src/query/dispatcher.rs index bcd3d0322d07c..840b09024ffa9 100644 --- a/compiler/rustc_query_system/src/query/dispatcher.rs +++ b/compiler/rustc_query_system/src/query/dispatcher.rs @@ -5,7 +5,7 @@ use rustc_data_structures::fingerprint::Fingerprint; use rustc_span::ErrorGuaranteed; use super::QueryStackFrameExtra; -use crate::dep_graph::{DepKind, DepNode, DepNodeParams, HasDepContext, SerializedDepNodeIndex}; +use crate::dep_graph::{DepKind, DepNode, DepNodeKey, HasDepContext, SerializedDepNodeIndex}; use crate::ich::StableHashingContext; use crate::query::caches::QueryCache; use crate::query::{CycleError, CycleErrorHandling, DepNodeIndex, QueryContext, QueryState}; @@ -33,7 +33,7 @@ pub trait QueryDispatcher<'tcx>: Copy + 'tcx { // `Key` and `Value` are `Copy` instead of `Clone` to ensure copying them stays cheap, // but it isn't necessary. - type Key: DepNodeParams> + Eq + Hash + Copy + Debug; + type Key: DepNodeKey> + Eq + Hash + Copy + Debug; type Value: Copy; type Cache: QueryCache; diff --git a/compiler/rustc_query_system/src/query/plumbing.rs b/compiler/rustc_query_system/src/query/plumbing.rs index fcd2e80a4fdc2..32c4f6e1c847c 100644 --- a/compiler/rustc_query_system/src/query/plumbing.rs +++ b/compiler/rustc_query_system/src/query/plumbing.rs @@ -18,7 +18,7 @@ use tracing::instrument; use super::{QueryDispatcher, QueryStackDeferred, QueryStackFrameExtra}; use crate::dep_graph::{ - DepContext, DepGraphData, DepNode, DepNodeIndex, DepNodeParams, HasDepContext, + DepContext, DepGraphData, DepNode, DepNodeIndex, DepNodeKey, HasDepContext, }; use crate::ich::StableHashingContext; use crate::query::caches::QueryCache; diff --git a/compiler/rustc_query_system/src/values.rs b/compiler/rustc_query_system/src/values.rs deleted file mode 100644 index 133904f59af14..0000000000000 --- a/compiler/rustc_query_system/src/values.rs +++ /dev/null @@ -1,21 +0,0 @@ -use rustc_span::ErrorGuaranteed; - -use crate::dep_graph::DepContext; -use crate::query::CycleError; - -pub trait Value: Sized { - fn from_cycle_error(tcx: Tcx, cycle_error: &CycleError, guar: ErrorGuaranteed) -> Self; -} - -impl Value for T { - default fn from_cycle_error(tcx: Tcx, cycle_error: &CycleError, _guar: ErrorGuaranteed) -> T { - tcx.sess().dcx().abort_if_errors(); - // Ideally we would use `bug!` here. But bug! is only defined in rustc_middle, and it's - // non-trivial to define it earlier. - panic!( - "<{} as Value>::from_cycle_error called without errors: {:#?}", - std::any::type_name::(), - cycle_error.cycle, - ); - } -} diff --git a/compiler/rustc_resolve/Cargo.toml b/compiler/rustc_resolve/Cargo.toml index dd15e879c6440..01e268d911d24 100644 --- a/compiler/rustc_resolve/Cargo.toml +++ b/compiler/rustc_resolve/Cargo.toml @@ -16,7 +16,6 @@ rustc_data_structures = { path = "../rustc_data_structures" } rustc_errors = { path = "../rustc_errors" } rustc_expand = { path = "../rustc_expand" } rustc_feature = { path = "../rustc_feature" } -rustc_fluent_macro = { path = "../rustc_fluent_macro" } rustc_hir = { path = "../rustc_hir" } rustc_index = { path = "../rustc_index" } rustc_macros = { path = "../rustc_macros" } diff --git a/compiler/rustc_resolve/messages.ftl b/compiler/rustc_resolve/messages.ftl deleted file mode 100644 index 4a980b2bd747d..0000000000000 --- a/compiler/rustc_resolve/messages.ftl +++ /dev/null @@ -1,531 +0,0 @@ -resolve_accessible_unsure = not sure whether the path is accessible or not - .note = the type may have associated items, but we are currently not checking them - -resolve_add_as_non_derive = - add as non-Derive macro - `#[{$macro_path}]` - -resolve_added_macro_use = - have you added the `#[macro_use]` on the module/import? - -resolve_ancestor_only = - visibilities can only be restricted to ancestor modules - -resolve_anonymous_lifetime_non_gat_report_error = missing lifetime in associated type - .label = this lifetime must come from the implemented type - .note = in the trait the associated type is declared without lifetime parameters, so using a borrowed type for them requires that lifetime to come from the implemented type - -resolve_arguments_macro_use_not_allowed = arguments to `macro_use` are not allowed here - -resolve_associated_const_with_similar_name_exists = - there is an associated constant with a similar name - -resolve_associated_fn_with_similar_name_exists = - there is an associated function with a similar name - -resolve_associated_type_with_similar_name_exists = - there is an associated type with a similar name - -resolve_attempt_to_use_non_constant_value_in_constant = - attempt to use a non-constant value in a constant - -resolve_attempt_to_use_non_constant_value_in_constant_label_with_suggestion = - non-constant value - -resolve_attempt_to_use_non_constant_value_in_constant_with_suggestion = - consider using `{$suggestion}` instead of `{$current}` - -resolve_attempt_to_use_non_constant_value_in_constant_without_suggestion = - this would need to be a `{$suggestion}` - -resolve_attributes_starting_with_rustc_are_reserved = - attributes starting with `rustc` are reserved for use by the `rustc` compiler - -resolve_binding_in_never_pattern = - never patterns cannot contain variable bindings - .suggestion = use a wildcard `_` instead - -resolve_binding_shadows_something_unacceptable = - {$shadowing_binding}s cannot shadow {$shadowed_binding}s - .label = cannot be named the same as {$article} {$shadowed_binding} - .label_shadowed_binding = the {$shadowed_binding} `{$name}` is {$participle} here - -resolve_binding_shadows_something_unacceptable_suggestion = - try specify the pattern arguments - -resolve_cannot_be_reexported_crate_public = - `{$ident}` is only public within the crate, and cannot be re-exported outside - -resolve_cannot_be_reexported_private = - `{$ident}` is private, and cannot be re-exported - -resolve_cannot_capture_dynamic_environment_in_fn_item = - can't capture dynamic environment in a fn item - .help = use the `|| {"{"} ... {"}"}` closure form instead - -resolve_cannot_determine_import_resolution = - cannot determine resolution for the import - .note = import resolution is stuck, try simplifying other imports - -resolve_cannot_determine_macro_resolution = - cannot determine resolution for the {$kind} `{$path}` - .note = import resolution is stuck, try simplifying macro imports - -resolve_cannot_find_builtin_macro_with_name = - cannot find a built-in macro with name `{$ident}` - -resolve_cannot_find_ident_in_this_scope = - cannot find {$expected} `{$ident}` in this scope - -resolve_cannot_glob_import_possible_crates = - cannot glob-import all possible crates - -resolve_cannot_use_through_an_import = - cannot use {$article} {$descr} through an import - .note = the {$descr} imported here - -resolve_change_import_binding = - you can use `as` to change the binding name of the import - -resolve_consider_adding_a_derive = - consider adding a derive - -resolve_consider_adding_macro_export = - consider adding a `#[macro_export]` to the macro in the imported module - -resolve_consider_declaring_with_pub = - consider declaring type or module `{$ident}` with `pub` - -resolve_consider_making_the_field_public = - { $number_of_fields -> - [one] consider making the field publicly accessible - *[other] consider making the fields publicly accessible - } - -resolve_consider_marking_as_pub = - consider marking `{$ident}` as `pub` in the imported module - -resolve_consider_marking_as_pub_crate = - in case you want to use the macro within this crate only, reduce the visibility to `pub(crate)` - -resolve_consider_move_macro_position = - consider moving the definition of `{$ident}` before this call - - -resolve_const_not_member_of_trait = - const `{$const_}` is not a member of trait `{$trait_}` - .label = not a member of trait `{$trait_}` - -resolve_const_param_in_enum_discriminant = - const parameters may not be used in enum discriminant values - -resolve_const_param_in_non_trivial_anon_const = - const parameters may only be used as standalone arguments here, i.e. `{$name}` - -resolve_constructor_private_if_any_field_private = - a constructor is private if any of the fields is private - -resolve_elided_anonymous_lifetime_report_error = - `&` without an explicit lifetime name cannot be used here - .label = explicit lifetime name needed here - -resolve_elided_anonymous_lifetime_report_error_suggestion = - consider introducing a higher-ranked lifetime here - -resolve_expected_module_found = - expected module, found {$res} `{$path_str}` - .label = not a module - -resolve_explicit_anonymous_lifetime_report_error = - `'_` cannot be used here - .label = `'_` is a reserved lifetime name - -resolve_explicit_unsafe_traits = - unsafe traits like `{$ident}` should be implemented explicitly - -resolve_extern_crate_loading_macro_not_at_crate_root = - an `extern crate` loading macros must be at the crate root - -resolve_extern_crate_not_idiomatic = `extern crate` is not idiomatic in the new edition - .suggestion = convert it to a `use` - -resolve_extern_crate_self_requires_renaming = - `extern crate self;` requires renaming - .suggestion = rename the `self` crate to be able to import it - -resolve_forward_declared_generic_in_const_param_ty = - const parameter types cannot reference parameters before they are declared - .label = const parameter type cannot reference `{$param}` before it is declared - -resolve_forward_declared_generic_param = - generic parameter defaults cannot reference parameters before they are declared - .label = cannot reference `{$param}` before it is declared - -resolve_found_an_item_configured_out = - found an item that was configured out - -resolve_generic_arguments_in_macro_path = - generic arguments in macro path - -resolve_generic_params_from_outer_item = - can't use {$is_self -> - [true] `Self` - *[false] generic parameters - } from outer item - .label = use of {$is_self -> - [true] `Self` - *[false] generic parameter - } from outer item - .refer_to_type_directly = refer to the type directly here instead - .suggestion = try introducing a local generic parameter here - .note = nested items are independent from their parent item for everything except for privacy and name resolution - -resolve_generic_params_from_outer_item_const = a `const` is a separate item from the item that contains it - -resolve_generic_params_from_outer_item_const_param = const parameter from outer item - -resolve_generic_params_from_outer_item_inner_item = {$is_self -> - [true] `Self` - *[false] generic parameter - } used in this inner {$descr} - -resolve_generic_params_from_outer_item_self_ty_alias = `Self` type implicitly declared here, by this `impl` - -resolve_generic_params_from_outer_item_self_ty_param = can't use `Self` here - -resolve_generic_params_from_outer_item_static = a `static` is a separate item from the item that contains it - -resolve_generic_params_from_outer_item_ty_param = type parameter from outer item - -resolve_ident_bound_more_than_once_in_parameter_list = - identifier `{$identifier}` is bound more than once in this parameter list - .label = used as parameter more than once - -resolve_ident_bound_more_than_once_in_same_pattern = - identifier `{$identifier}` is bound more than once in the same pattern - .label = used in a pattern more than once - -resolve_ident_imported_here_but_it_is_desc = - `{$imported_ident}` is imported here, but it is {$imported_ident_desc} - -resolve_ident_in_scope_but_it_is_desc = - `{$imported_ident}` is in scope, but it is {$imported_ident_desc} - -resolve_implicit_elided_lifetimes_not_allowed_here = implicit elided lifetime not allowed here - -resolve_imported_crate = `$crate` may not be imported - -resolve_imported_macro_not_found = imported macro not found - -resolve_imports_cannot_refer_to = - imports cannot refer to {$what} - -resolve_indeterminate = - cannot determine resolution for the visibility - -resolve_invalid_asm_sym = - invalid `sym` operand - .label = is a local variable - .help = `sym` operands must refer to either a function or a static - -resolve_is_private = - {$ident_descr} `{$ident}` is private - .label = private {$ident_descr} - -resolve_item_was_behind_feature = - the item is gated behind the `{$feature}` feature - -resolve_item_was_cfg_out = the item is gated here - -resolve_label_with_similar_name_reachable = - a label with a similar name is reachable - -resolve_legacy_derive_helpers = derive helper attribute is used before it is introduced - .label = the attribute is introduced here - -resolve_lending_iterator_report_error = - associated type `Iterator::Item` is declared without lifetime parameters, so using a borrowed type for them requires that lifetime to come from the implemented type - .note = you can't create an `Iterator` that borrows each `Item` from itself, but you can instead create a new type that borrows your existing type and implement `Iterator` for that new type - -resolve_lifetime_param_in_enum_discriminant = - lifetime parameters may not be used in enum discriminant values - -resolve_lifetime_param_in_non_trivial_anon_const = - lifetime parameters may not be used in const expressions - -resolve_lowercase_self = - attempt to use a non-constant value in a constant - .suggestion = try using `Self` - -resolve_macro_cannot_use_as_attr = - `{$ident}` exists, but has no `attr` rules - -resolve_macro_cannot_use_as_derive = - `{$ident}` exists, but has no `derive` rules - -resolve_macro_cannot_use_as_fn_like = - `{$ident}` exists, but has no rules for function-like invocation - -resolve_macro_defined_later = - a macro with the same name exists, but it appears later - -resolve_macro_expanded_extern_crate_cannot_shadow_extern_arguments = - macro-expanded `extern crate` items cannot shadow names passed with `--extern` - -resolve_macro_expanded_macro_exports_accessed_by_absolute_paths = macro-expanded `macro_export` macros from the current crate cannot be referred to by absolute paths - .note = the macro is defined here - -resolve_macro_expected_found = - expected {$expected}, found {$found} `{$macro_path}` - .label = not {$article} {$expected} - -resolve_macro_extern_deprecated = - `#[macro_escape]` is a deprecated synonym for `#[macro_use]` - .help = try an outer attribute: `#[macro_use]` - -resolve_macro_is_private = macro `{$ident}` is private - -resolve_macro_rule_never_used = rule #{$n} of macro `{$name}` is never used - -resolve_macro_use_deprecated = - applying the `#[macro_use]` attribute to an `extern crate` item is deprecated - .help = remove it and import macros at use sites with a `use` item instead - -resolve_macro_use_extern_crate_self = `#[macro_use]` is not supported on `extern crate self` - -resolve_macro_use_name_already_in_use = - `{$name}` is already in scope - .note = macro-expanded `#[macro_use]`s may not shadow existing macros (see RFC 1560) - -resolve_method_not_member_of_trait = - method `{$method}` is not a member of trait `{$trait_}` - .label = not a member of trait `{$trait_}` - -resolve_missing_macro_rules_name = maybe you have forgotten to define a name for this `macro_rules!` - -resolve_module_only = - visibility must resolve to a module - -resolve_name_defined_multiple_time = - the name `{$name}` is defined multiple times - .note = `{$name}` must be defined only once in the {$descr} namespace of this {$container} - -resolve_name_defined_multiple_time_old_binding_definition = - previous definition of the {$old_kind} `{$name}` here - -resolve_name_defined_multiple_time_old_binding_import = - previous import of the {$old_kind} `{$name}` here - -resolve_name_defined_multiple_time_redefined = - `{$name}` redefined here - -resolve_name_defined_multiple_time_reimported = - `{$name}` reimported here - -resolve_name_is_already_used_as_generic_parameter = - the name `{$name}` is already used for a generic parameter in this item's generic parameters - .label = already used - .first_use_of_name = first use of `{$name}` - -resolve_name_reserved_in_attribute_namespace = - name `{$ident}` is reserved in attribute namespace - -resolve_note_and_refers_to_the_item_defined_here = - {$first -> - [true] {$dots -> - [true] the {$binding_descr} `{$binding_name}` is defined here... - *[false] the {$binding_descr} `{$binding_name}` is defined here - } - *[false] {$dots -> - [true] ...and refers to the {$binding_descr} `{$binding_name}` which is defined here... - *[false] ...and refers to the {$binding_descr} `{$binding_name}` which is defined here - } - } - -resolve_out_of_scope_macro_calls = cannot find macro `{$path}` in the current scope when looking from {$location} - .label = not found from {$location} - .help = import `macro_rules` with `use` to make it callable above its definition - -resolve_outer_ident_is_not_publicly_reexported = - {$outer_ident_descr} `{$outer_ident}` is not publicly re-exported - -resolve_param_in_enum_discriminant = - generic parameters may not be used in enum discriminant values - .label = cannot perform const operation using `{$name}` - -resolve_param_in_non_trivial_anon_const = - generic parameters may not be used in const operations - .label = cannot perform const operation using `{$name}` - -resolve_param_in_non_trivial_anon_const_help = - add `#![feature(generic_const_exprs)]` to allow generic const expressions - -resolve_param_in_ty_of_const_param = - the type of const parameters must not depend on other generic parameters - .label = the type must not depend on the parameter `{$name}` - -resolve_pattern_doesnt_bind_name = pattern doesn't bind `{$name}` - -resolve_private_extern_crate_reexport = extern crate `{$ident}` is private and cannot be re-exported - .suggestion = consider making the `extern crate` item publicly accessible - -resolve_proc_macro_derive_resolution_fallback = cannot find {$ns_descr} `{$ident}` in this scope - .label = names from parent modules are not accessible without an explicit import - -resolve_proc_macro_same_crate = can't use a procedural macro from the same crate that defines it - .help = you can define integration tests in a directory named `tests` - -resolve_redundant_import_visibility = glob import doesn't reexport anything with visibility `{$import_vis}` because no imported item is public enough - .note = the most public imported item is `{$max_vis}` - .help = reduce the glob import's visibility or increase visibility of imported items - -resolve_reexport_of_crate_public = - re-export of crate public `{$ident}` - -resolve_reexport_of_private = - re-export of private `{$ident}` - -resolve_reexport_private_dependency = - {$kind} `{$name}` from private dependency '{$krate}' is re-exported - -resolve_relative_2018 = - relative paths are not supported in visibilities in 2018 edition or later - .suggestion = try - -resolve_remove_surrounding_derive = - remove from the surrounding `derive()` - -resolve_remove_unnecessary_import = remove unnecessary import - -resolve_self_import_can_only_appear_once_in_the_list = - `self` import can only appear once in an import list - .label = can only appear once in an import list - -resolve_self_import_only_in_import_list_with_non_empty_prefix = - `self` import can only appear in an import list with a non-empty prefix - .label = can only appear in an import list with a non-empty prefix - -resolve_self_imports_only_allowed_within = - `self` imports are only allowed within a {"{"} {"}"} list - -resolve_self_imports_only_allowed_within_multipart_suggestion = - alternatively, use the multi-path `use` syntax to import `self` - -resolve_self_imports_only_allowed_within_suggestion = - consider importing the module directly - -resolve_self_in_const_generic_ty = - cannot use `Self` in const parameter type - -resolve_self_in_generic_param_default = - generic parameters cannot use `Self` in their defaults - -resolve_similarly_named_defined_here = - similarly named {$candidate_descr} `{$candidate}` defined here - -resolve_single_item_defined_here = - {$candidate_descr} `{$candidate}` defined here - -resolve_static_lifetime_is_reserved = invalid lifetime parameter name: `{$lifetime}` - .label = 'static is a reserved lifetime name - -resolve_suggestion_import_ident_directly = - import `{$ident}` directly - -resolve_suggestion_import_ident_through_reexport = - import `{$ident}` through the re-export - -resolve_tool_module_imported = - cannot use a tool module through an import - .note = the tool module imported here - -resolve_tool_only_accepts_identifiers = - `{$tool}` only accepts identifiers - .label = not an identifier - -resolve_tool_was_already_registered = - tool `{$tool}` was already registered - .label = already registered here - -resolve_trait_impl_duplicate = - duplicate definitions with name `{$name}`: - .label = duplicate definition - .old_span_label = previous definition here - .trait_item_span = item in trait - -resolve_trait_impl_mismatch = - item `{$name}` is an associated {$kind}, which doesn't match its trait `{$trait_path}` - .label = does not match trait - .trait_impl_mismatch_label_item = item in trait -resolve_try_using_similarly_named_label = - try using similarly named label - -resolve_type_not_member_of_trait = - type `{$type_}` is not a member of trait `{$trait_}` - .label = not a member of trait `{$trait_}` - -resolve_type_param_in_enum_discriminant = - type parameters may not be used in enum discriminant values - -resolve_type_param_in_non_trivial_anon_const = - type parameters may not be used in const expressions - -resolve_undeclared_label = - use of undeclared label `{$name}` - .label = undeclared label `{$name}` - -resolve_underscore_lifetime_is_reserved = `'_` cannot be used here - .label = `'_` is a reserved lifetime name - .help = use another lifetime specifier - -resolve_unexpected_res_change_ty_to_const_param_sugg = - you might have meant to write a const parameter here - -resolve_unexpected_res_use_at_op_in_slice_pat_with_range_sugg = - if you meant to collect the rest of the slice in `{$ident}`, use the at operator - -resolve_unknown_diagnostic_attribute = unknown diagnostic attribute -resolve_unknown_diagnostic_attribute_typo_sugg = an attribute with a similar name exists - -resolve_unnamed_crate_root_import = - crate root imports need to be explicitly named: `use crate as name;` - -resolve_unreachable_label = - use of unreachable label `{$name}` - .label = unreachable label `{$name}` - .label_definition_span = unreachable label defined here - .note = labels are unreachable through functions, closures, async blocks and modules - -resolve_unreachable_label_similar_name_reachable = - a label with a similar name is reachable - -resolve_unreachable_label_similar_name_unreachable = - a label with a similar name exists but is also unreachable - -resolve_unreachable_label_suggestion_use_similarly_named = - try using similarly named label - -resolve_unreachable_label_with_similar_name_exists = - a label with a similar name exists but is unreachable - -resolve_unused_extern_crate = unused extern crate - .label = unused - .suggestion = remove the unused `extern crate` - -resolve_unused_label = unused label - -resolve_unused_macro_definition = unused macro definition: `{$name}` - -resolve_unused_macro_use = unused `#[macro_use]` import - -resolve_variable_bound_with_different_mode = - variable `{$variable_name}` is bound inconsistently across alternatives separated by `|` - .label = bound in different ways - .first_binding_span = first binding - -resolve_variable_is_a_typo = you might have meant to use the similarly named previously used binding `{$typo}` - -resolve_variable_is_not_bound_in_all_patterns = - variable `{$name}` is not bound in all patterns - -resolve_variable_not_in_all_patterns = variable not in all patterns diff --git a/compiler/rustc_resolve/src/errors.rs b/compiler/rustc_resolve/src/errors.rs index 3e54464030527..7afdbf6a469f8 100644 --- a/compiler/rustc_resolve/src/errors.rs +++ b/compiler/rustc_resolve/src/errors.rs @@ -1,21 +1,31 @@ use rustc_errors::codes::*; use rustc_errors::{ Applicability, Diag, DiagCtxtHandle, DiagMessage, Diagnostic, ElidedLifetimeInPathSubdiag, - EmissionGuarantee, IntoDiagArg, Level, LintDiagnostic, MultiSpan, Subdiagnostic, + EmissionGuarantee, IntoDiagArg, Level, LintDiagnostic, MultiSpan, Subdiagnostic, inline_fluent, }; use rustc_macros::{Diagnostic, LintDiagnostic, Subdiagnostic}; use rustc_span::source_map::Spanned; use rustc_span::{Ident, Span, Symbol}; +use crate::Res; use crate::late::PatternSource; -use crate::{Res, fluent_generated as fluent}; #[derive(Diagnostic)] -#[diag(resolve_generic_params_from_outer_item, code = E0401)] -#[note] +#[diag("can't use {$is_self -> + [true] `Self` + *[false] generic parameters + } from outer item", code = E0401)] +#[note( + "nested items are independent from their parent item for everything except for privacy and name resolution" +)] pub(crate) struct GenericParamsFromOuterItem { #[primary_span] - #[label] + #[label( + "use of {$is_self -> + [true] `Self` + *[false] generic parameter + } from outer item" + )] pub(crate) span: Span, #[subdiagnostic] pub(crate) label: Option, @@ -31,7 +41,12 @@ pub(crate) struct GenericParamsFromOuterItem { } #[derive(Subdiagnostic)] -#[label(resolve_generic_params_from_outer_item_inner_item)] +#[label( + "{$is_self -> + [true] `Self` + *[false] generic parameter + } used in this inner {$descr}" +)] pub(crate) struct GenericParamsFromOuterItemInnerItem { #[primary_span] pub(crate) span: Span, @@ -40,27 +55,27 @@ pub(crate) struct GenericParamsFromOuterItemInnerItem { #[derive(Subdiagnostic)] pub(crate) enum GenericParamsFromOuterItemStaticOrConst { - #[note(resolve_generic_params_from_outer_item_static)] + #[note("a `static` is a separate item from the item that contains it")] Static, - #[note(resolve_generic_params_from_outer_item_const)] + #[note("a `const` is a separate item from the item that contains it")] Const, } #[derive(Subdiagnostic)] pub(crate) enum GenericParamsFromOuterItemLabel { - #[label(resolve_generic_params_from_outer_item_self_ty_param)] + #[label("can't use `Self` here")] SelfTyParam(#[primary_span] Span), - #[label(resolve_generic_params_from_outer_item_self_ty_alias)] + #[label("`Self` type implicitly declared here, by this `impl`")] SelfTyAlias(#[primary_span] Span), - #[label(resolve_generic_params_from_outer_item_ty_param)] + #[label("type parameter from outer item")] TyParam(#[primary_span] Span), - #[label(resolve_generic_params_from_outer_item_const_param)] + #[label("const parameter from outer item")] ConstParam(#[primary_span] Span), } #[derive(Subdiagnostic)] #[suggestion( - resolve_suggestion, + "try introducing a local generic parameter here", code = "{snippet}", applicability = "maybe-incorrect", style = "verbose" @@ -72,7 +87,7 @@ pub(crate) struct GenericParamsFromOuterItemSugg { } #[derive(Subdiagnostic)] #[suggestion( - resolve_refer_to_type_directly, + "refer to the type directly here instead", code = "{snippet}", applicability = "maybe-incorrect", style = "verbose" @@ -84,21 +99,21 @@ pub(crate) struct UseTypeDirectly { } #[derive(Diagnostic)] -#[diag(resolve_name_is_already_used_as_generic_parameter, code = E0403)] +#[diag("the name `{$name}` is already used for a generic parameter in this item's generic parameters", code = E0403)] pub(crate) struct NameAlreadyUsedInParameterList { #[primary_span] - #[label] + #[label("already used")] pub(crate) span: Span, - #[label(resolve_first_use_of_name)] + #[label("first use of `{$name}`")] pub(crate) first_use_span: Span, pub(crate) name: Ident, } #[derive(Diagnostic)] -#[diag(resolve_method_not_member_of_trait, code = E0407)] +#[diag("method `{$method}` is not a member of trait `{$trait_}`", code = E0407)] pub(crate) struct MethodNotMemberOfTrait { #[primary_span] - #[label] + #[label("not a member of trait `{$trait_}`")] pub(crate) span: Span, pub(crate) method: Ident, pub(crate) trait_: String, @@ -108,7 +123,7 @@ pub(crate) struct MethodNotMemberOfTrait { #[derive(Subdiagnostic)] #[suggestion( - resolve_associated_fn_with_similar_name_exists, + "there is an associated function with a similar name", code = "{candidate}", applicability = "maybe-incorrect" )] @@ -119,10 +134,10 @@ pub(crate) struct AssociatedFnWithSimilarNameExists { } #[derive(Diagnostic)] -#[diag(resolve_type_not_member_of_trait, code = E0437)] +#[diag("type `{$type_}` is not a member of trait `{$trait_}`", code = E0437)] pub(crate) struct TypeNotMemberOfTrait { #[primary_span] - #[label] + #[label("not a member of trait `{$trait_}`")] pub(crate) span: Span, pub(crate) type_: Ident, pub(crate) trait_: String, @@ -132,7 +147,7 @@ pub(crate) struct TypeNotMemberOfTrait { #[derive(Subdiagnostic)] #[suggestion( - resolve_associated_type_with_similar_name_exists, + "there is an associated type with a similar name", code = "{candidate}", applicability = "maybe-incorrect" )] @@ -143,10 +158,10 @@ pub(crate) struct AssociatedTypeWithSimilarNameExists { } #[derive(Diagnostic)] -#[diag(resolve_const_not_member_of_trait, code = E0438)] +#[diag("const `{$const_}` is not a member of trait `{$trait_}`", code = E0438)] pub(crate) struct ConstNotMemberOfTrait { #[primary_span] - #[label] + #[label("not a member of trait `{$trait_}`")] pub(crate) span: Span, pub(crate) const_: Ident, pub(crate) trait_: String, @@ -156,7 +171,7 @@ pub(crate) struct ConstNotMemberOfTrait { #[derive(Subdiagnostic)] #[suggestion( - resolve_associated_const_with_similar_name_exists, + "there is an associated constant with a similar name", code = "{candidate}", applicability = "maybe-incorrect" )] @@ -167,39 +182,39 @@ pub(crate) struct AssociatedConstWithSimilarNameExists { } #[derive(Diagnostic)] -#[diag(resolve_variable_bound_with_different_mode, code = E0409)] +#[diag("variable `{$variable_name}` is bound inconsistently across alternatives separated by `|`", code = E0409)] pub(crate) struct VariableBoundWithDifferentMode { #[primary_span] - #[label] + #[label("bound in different ways")] pub(crate) span: Span, - #[label(resolve_first_binding_span)] + #[label("first binding")] pub(crate) first_binding_span: Span, pub(crate) variable_name: Ident, } #[derive(Diagnostic)] -#[diag(resolve_ident_bound_more_than_once_in_parameter_list, code = E0415)] +#[diag("identifier `{$identifier}` is bound more than once in this parameter list", code = E0415)] pub(crate) struct IdentifierBoundMoreThanOnceInParameterList { #[primary_span] - #[label] + #[label("used as parameter more than once")] pub(crate) span: Span, pub(crate) identifier: Ident, } #[derive(Diagnostic)] -#[diag(resolve_ident_bound_more_than_once_in_same_pattern, code = E0416)] +#[diag("identifier `{$identifier}` is bound more than once in the same pattern", code = E0416)] pub(crate) struct IdentifierBoundMoreThanOnceInSamePattern { #[primary_span] - #[label] + #[label("used in a pattern more than once")] pub(crate) span: Span, pub(crate) identifier: Ident, } #[derive(Diagnostic)] -#[diag(resolve_undeclared_label, code = E0426)] +#[diag("use of undeclared label `{$name}`", code = E0426)] pub(crate) struct UndeclaredLabel { #[primary_span] - #[label] + #[label("undeclared label `{$name}`")] pub(crate) span: Span, pub(crate) name: Symbol, #[subdiagnostic] @@ -211,12 +226,12 @@ pub(crate) struct UndeclaredLabel { } #[derive(Subdiagnostic)] -#[label(resolve_label_with_similar_name_reachable)] +#[label("a label with a similar name is reachable")] pub(crate) struct LabelWithSimilarNameReachable(#[primary_span] pub(crate) Span); #[derive(Subdiagnostic)] #[suggestion( - resolve_try_using_similarly_named_label, + "try using similarly named label", code = "{ident_name}", applicability = "maybe-incorrect" )] @@ -227,38 +242,38 @@ pub(crate) struct TryUsingSimilarlyNamedLabel { } #[derive(Subdiagnostic)] -#[label(resolve_unreachable_label_with_similar_name_exists)] +#[label("a label with a similar name exists but is unreachable")] pub(crate) struct UnreachableLabelWithSimilarNameExists { #[primary_span] pub(crate) ident_span: Span, } #[derive(Diagnostic)] -#[diag(resolve_self_import_can_only_appear_once_in_the_list, code = E0430)] +#[diag("`self` import can only appear once in an import list", code = E0430)] pub(crate) struct SelfImportCanOnlyAppearOnceInTheList { #[primary_span] - #[label] + #[label("can only appear once in an import list")] pub(crate) span: Span, } #[derive(Diagnostic)] -#[diag(resolve_self_import_only_in_import_list_with_non_empty_prefix, code = E0431)] +#[diag("`self` import can only appear in an import list with a non-empty prefix", code = E0431)] pub(crate) struct SelfImportOnlyInImportListWithNonEmptyPrefix { #[primary_span] - #[label] + #[label("can only appear in an import list with a non-empty prefix")] pub(crate) span: Span, } #[derive(Diagnostic)] -#[diag(resolve_cannot_capture_dynamic_environment_in_fn_item, code = E0434)] -#[help] +#[diag("can't capture dynamic environment in a fn item", code = E0434)] +#[help("use the `|| {\"{\"} ... {\"}\"}` closure form instead")] pub(crate) struct CannotCaptureDynamicEnvironmentInFnItem { #[primary_span] pub(crate) span: Span, } #[derive(Diagnostic)] -#[diag(resolve_attempt_to_use_non_constant_value_in_constant, code = E0435)] +#[diag("attempt to use a non-constant value in a constant", code = E0435)] pub(crate) struct AttemptToUseNonConstantValueInConstant<'a> { #[primary_span] pub(crate) span: Span, @@ -272,7 +287,7 @@ pub(crate) struct AttemptToUseNonConstantValueInConstant<'a> { #[derive(Subdiagnostic)] #[multipart_suggestion( - resolve_attempt_to_use_non_constant_value_in_constant_with_suggestion, + "consider using `{$suggestion}` instead of `{$current}`", style = "verbose", applicability = "has-placeholders" )] @@ -287,14 +302,14 @@ pub(crate) struct AttemptToUseNonConstantValueInConstantWithSuggestion<'a> { } #[derive(Subdiagnostic)] -#[label(resolve_attempt_to_use_non_constant_value_in_constant_label_with_suggestion)] +#[label("non-constant value")] pub(crate) struct AttemptToUseNonConstantValueInConstantLabelWithSuggestion { #[primary_span] pub(crate) span: Span, } #[derive(Subdiagnostic)] -#[label(resolve_attempt_to_use_non_constant_value_in_constant_without_suggestion)] +#[label("this would need to be a `{$suggestion}`")] pub(crate) struct AttemptToUseNonConstantValueInConstantWithoutSuggestion<'a> { #[primary_span] pub(crate) ident_span: Span, @@ -302,7 +317,7 @@ pub(crate) struct AttemptToUseNonConstantValueInConstantWithoutSuggestion<'a> { } #[derive(Diagnostic)] -#[diag(resolve_self_imports_only_allowed_within, code = E0429)] +#[diag("`self` imports are only allowed within a {\"{\"} {\"}\"} list", code = E0429)] pub(crate) struct SelfImportsOnlyAllowedWithin { #[primary_span] pub(crate) span: Span, @@ -314,7 +329,7 @@ pub(crate) struct SelfImportsOnlyAllowedWithin { #[derive(Subdiagnostic)] #[suggestion( - resolve_self_imports_only_allowed_within_suggestion, + "consider importing the module directly", code = "", applicability = "machine-applicable" )] @@ -325,7 +340,7 @@ pub(crate) struct SelfImportsOnlyAllowedWithinSuggestion { #[derive(Subdiagnostic)] #[multipart_suggestion( - resolve_self_imports_only_allowed_within_multipart_suggestion, + "alternatively, use the multi-path `use` syntax to import `self`", applicability = "machine-applicable" )] pub(crate) struct SelfImportsOnlyAllowedWithinMultipartSuggestion { @@ -336,17 +351,17 @@ pub(crate) struct SelfImportsOnlyAllowedWithinMultipartSuggestion { } #[derive(Diagnostic)] -#[diag(resolve_binding_shadows_something_unacceptable, code = E0530)] +#[diag("{$shadowing_binding}s cannot shadow {$shadowed_binding}s", code = E0530)] pub(crate) struct BindingShadowsSomethingUnacceptable<'a> { #[primary_span] - #[label] + #[label("cannot be named the same as {$article} {$shadowed_binding}")] pub(crate) span: Span, pub(crate) shadowing_binding: PatternSource, pub(crate) shadowed_binding: Res, pub(crate) article: &'a str, #[subdiagnostic] pub(crate) sub_suggestion: Option, - #[label(resolve_label_shadowed_binding)] + #[label("the {$shadowed_binding} `{$name}` is {$participle} here")] pub(crate) shadowed_binding_span: Span, pub(crate) participle: &'a str, pub(crate) name: Symbol, @@ -354,7 +369,7 @@ pub(crate) struct BindingShadowsSomethingUnacceptable<'a> { #[derive(Subdiagnostic)] #[suggestion( - resolve_binding_shadows_something_unacceptable_suggestion, + "try specify the pattern arguments", code = "{name}(..)", applicability = "unspecified" )] @@ -365,51 +380,51 @@ pub(crate) struct BindingShadowsSomethingUnacceptableSuggestion { } #[derive(Diagnostic)] -#[diag(resolve_forward_declared_generic_param, code = E0128)] +#[diag("generic parameter defaults cannot reference parameters before they are declared", code = E0128)] pub(crate) struct ForwardDeclaredGenericParam { #[primary_span] - #[label] + #[label("cannot reference `{$param}` before it is declared")] pub(crate) span: Span, pub(crate) param: Symbol, } #[derive(Diagnostic)] -#[diag(resolve_forward_declared_generic_in_const_param_ty)] +#[diag("const parameter types cannot reference parameters before they are declared")] pub(crate) struct ForwardDeclaredGenericInConstParamTy { #[primary_span] - #[label] + #[label("const parameter type cannot reference `{$param}` before it is declared")] pub(crate) span: Span, pub(crate) param: Symbol, } #[derive(Diagnostic)] -#[diag(resolve_param_in_ty_of_const_param, code = E0770)] +#[diag("the type of const parameters must not depend on other generic parameters", code = E0770)] pub(crate) struct ParamInTyOfConstParam { #[primary_span] - #[label] + #[label("the type must not depend on the parameter `{$name}`")] pub(crate) span: Span, pub(crate) name: Symbol, } #[derive(Diagnostic)] -#[diag(resolve_self_in_generic_param_default, code = E0735)] +#[diag("generic parameters cannot use `Self` in their defaults", code = E0735)] pub(crate) struct SelfInGenericParamDefault { #[primary_span] pub(crate) span: Span, } #[derive(Diagnostic)] -#[diag(resolve_self_in_const_generic_ty)] +#[diag("cannot use `Self` in const parameter type")] pub(crate) struct SelfInConstGenericTy { #[primary_span] pub(crate) span: Span, } #[derive(Diagnostic)] -#[diag(resolve_param_in_non_trivial_anon_const)] +#[diag("generic parameters may not be used in const operations")] pub(crate) struct ParamInNonTrivialAnonConst { #[primary_span] - #[label] + #[label("cannot perform const operation using `{$name}`")] pub(crate) span: Span, pub(crate) name: Symbol, #[subdiagnostic] @@ -419,29 +434,29 @@ pub(crate) struct ParamInNonTrivialAnonConst { } #[derive(Subdiagnostic)] -#[help(resolve_param_in_non_trivial_anon_const_help)] +#[help("add `#![feature(generic_const_exprs)]` to allow generic const expressions")] pub(crate) struct ParamInNonTrivialAnonConstHelp; #[derive(Debug)] #[derive(Subdiagnostic)] pub(crate) enum ParamKindInNonTrivialAnonConst { - #[note(resolve_type_param_in_non_trivial_anon_const)] + #[note("type parameters may not be used in const expressions")] Type, - #[help(resolve_const_param_in_non_trivial_anon_const)] + #[help("const parameters may only be used as standalone arguments here, i.e. `{$name}`")] Const { name: Symbol }, - #[note(resolve_lifetime_param_in_non_trivial_anon_const)] + #[note("lifetime parameters may not be used in const expressions")] Lifetime, } #[derive(Diagnostic)] -#[diag(resolve_unreachable_label, code = E0767)] -#[note] +#[diag("use of unreachable label `{$name}`", code = E0767)] +#[note("labels are unreachable through functions, closures, async blocks and modules")] pub(crate) struct UnreachableLabel { #[primary_span] - #[label] + #[label("unreachable label `{$name}`")] pub(crate) span: Span, pub(crate) name: Symbol, - #[label(resolve_label_definition_span)] + #[label("unreachable label defined here")] pub(crate) definition_span: Span, #[subdiagnostic] pub(crate) sub_suggestion: Option, @@ -453,7 +468,7 @@ pub(crate) struct UnreachableLabel { #[derive(Subdiagnostic)] #[suggestion( - resolve_unreachable_label_suggestion_use_similarly_named, + "try using similarly named label", code = "{ident_name}", applicability = "maybe-incorrect" )] @@ -464,104 +479,114 @@ pub(crate) struct UnreachableLabelSubSuggestion { } #[derive(Subdiagnostic)] -#[label(resolve_unreachable_label_similar_name_reachable)] +#[label("a label with a similar name is reachable")] pub(crate) struct UnreachableLabelSubLabel { #[primary_span] pub(crate) ident_span: Span, } #[derive(Subdiagnostic)] -#[label(resolve_unreachable_label_similar_name_unreachable)] +#[label("a label with a similar name exists but is also unreachable")] pub(crate) struct UnreachableLabelSubLabelUnreachable { #[primary_span] pub(crate) ident_span: Span, } #[derive(Diagnostic)] -#[diag(resolve_invalid_asm_sym)] -#[help] +#[diag("invalid `sym` operand")] +#[help("`sym` operands must refer to either a function or a static")] pub(crate) struct InvalidAsmSym { #[primary_span] - #[label] + #[label("is a local variable")] pub(crate) span: Span, } #[derive(Diagnostic)] -#[diag(resolve_lowercase_self)] +#[diag("attempt to use a non-constant value in a constant")] pub(crate) struct LowercaseSelf { #[primary_span] - #[suggestion(code = "Self", applicability = "maybe-incorrect", style = "short")] + #[suggestion( + "try using `Self`", + code = "Self", + applicability = "maybe-incorrect", + style = "short" + )] pub(crate) span: Span, } #[derive(Debug)] #[derive(Diagnostic)] -#[diag(resolve_binding_in_never_pattern)] +#[diag("never patterns cannot contain variable bindings")] pub(crate) struct BindingInNeverPattern { #[primary_span] - #[suggestion(code = "_", applicability = "machine-applicable", style = "short")] + #[suggestion( + "use a wildcard `_` instead", + code = "_", + applicability = "machine-applicable", + style = "short" + )] pub(crate) span: Span, } #[derive(Diagnostic)] -#[diag(resolve_trait_impl_duplicate, code = E0201)] +#[diag("duplicate definitions with name `{$name}`:", code = E0201)] pub(crate) struct TraitImplDuplicate { #[primary_span] - #[label] + #[label("duplicate definition")] pub(crate) span: Span, - #[label(resolve_old_span_label)] + #[label("previous definition here")] pub(crate) old_span: Span, - #[label(resolve_trait_item_span)] + #[label("item in trait")] pub(crate) trait_item_span: Span, pub(crate) name: Ident, } #[derive(Diagnostic)] -#[diag(resolve_relative_2018)] +#[diag("relative paths are not supported in visibilities in 2018 edition or later")] pub(crate) struct Relative2018 { #[primary_span] pub(crate) span: Span, - #[suggestion(code = "crate::{path_str}", applicability = "maybe-incorrect")] + #[suggestion("try", code = "crate::{path_str}", applicability = "maybe-incorrect")] pub(crate) path_span: Span, pub(crate) path_str: String, } #[derive(Diagnostic)] -#[diag(resolve_ancestor_only, code = E0742)] +#[diag("visibilities can only be restricted to ancestor modules", code = E0742)] pub(crate) struct AncestorOnly(#[primary_span] pub(crate) Span); #[derive(Diagnostic)] -#[diag(resolve_expected_module_found, code = E0577)] +#[diag("expected module, found {$res} `{$path_str}`", code = E0577)] pub(crate) struct ExpectedModuleFound { #[primary_span] - #[label] + #[label("not a module")] pub(crate) span: Span, pub(crate) res: Res, pub(crate) path_str: String, } #[derive(Diagnostic)] -#[diag(resolve_indeterminate, code = E0578)] +#[diag("cannot determine resolution for the visibility", code = E0578)] pub(crate) struct Indeterminate(#[primary_span] pub(crate) Span); #[derive(Diagnostic)] -#[diag(resolve_tool_module_imported)] +#[diag("cannot use a tool module through an import")] pub(crate) struct ToolModuleImported { #[primary_span] pub(crate) span: Span, - #[note] + #[note("the tool module imported here")] pub(crate) import: Span, } #[derive(Diagnostic)] -#[diag(resolve_module_only)] +#[diag("visibility must resolve to a module")] pub(crate) struct ModuleOnly(#[primary_span] pub(crate) Span); #[derive(Diagnostic)] -#[diag(resolve_macro_expected_found)] +#[diag("expected {$expected}, found {$found} `{$macro_path}`")] pub(crate) struct MacroExpectedFound<'a> { #[primary_span] - #[label] + #[label("not {$article} {$expected}")] pub(crate) span: Span, pub(crate) found: &'a str, pub(crate) article: &'static str, @@ -574,60 +599,66 @@ pub(crate) struct MacroExpectedFound<'a> { } #[derive(Subdiagnostic)] -#[help(resolve_remove_surrounding_derive)] +#[help("remove from the surrounding `derive()`")] pub(crate) struct RemoveSurroundingDerive { #[primary_span] pub(crate) span: Span, } #[derive(Subdiagnostic)] -#[help(resolve_add_as_non_derive)] +#[help( + " + add as non-Derive macro + `#[{$macro_path}]`" +)] pub(crate) struct AddAsNonDerive<'a> { pub(crate) macro_path: &'a str, } #[derive(Diagnostic)] -#[diag(resolve_proc_macro_same_crate)] +#[diag("can't use a procedural macro from the same crate that defines it")] pub(crate) struct ProcMacroSameCrate { #[primary_span] pub(crate) span: Span, - #[help] + #[help("you can define integration tests in a directory named `tests`")] pub(crate) is_test: bool, } #[derive(LintDiagnostic)] -#[diag(resolve_proc_macro_derive_resolution_fallback)] +#[diag("cannot find {$ns_descr} `{$ident}` in this scope")] pub(crate) struct ProcMacroDeriveResolutionFallback { - #[label] + #[label("names from parent modules are not accessible without an explicit import")] pub span: Span, pub ns_descr: &'static str, pub ident: Symbol, } #[derive(LintDiagnostic)] -#[diag(resolve_macro_expanded_macro_exports_accessed_by_absolute_paths)] +#[diag( + "macro-expanded `macro_export` macros from the current crate cannot be referred to by absolute paths" +)] pub(crate) struct MacroExpandedMacroExportsAccessedByAbsolutePaths { - #[note] + #[note("the macro is defined here")] pub definition: Span, } #[derive(Diagnostic)] -#[diag(resolve_imported_crate)] +#[diag("`$crate` may not be imported")] pub(crate) struct CrateImported { #[primary_span] pub(crate) span: Span, } #[derive(Diagnostic)] -#[diag(resolve_macro_use_extern_crate_self)] +#[diag("`#[macro_use]` is not supported on `extern crate self`")] pub(crate) struct MacroUseExternCrateSelf { #[primary_span] pub(crate) span: Span, } #[derive(Diagnostic)] -#[diag(resolve_accessible_unsure)] -#[note] +#[diag("not sure whether the path is accessible or not")] +#[note("the type may have associated items, but we are currently not checking them")] pub(crate) struct CfgAccessibleUnsure { #[primary_span] pub(crate) span: Span, @@ -635,10 +666,10 @@ pub(crate) struct CfgAccessibleUnsure { #[derive(Debug)] #[derive(Diagnostic)] -#[diag(resolve_param_in_enum_discriminant)] +#[diag("generic parameters may not be used in enum discriminant values")] pub(crate) struct ParamInEnumDiscriminant { #[primary_span] - #[label] + #[label("cannot perform const operation using `{$name}`")] pub(crate) span: Span, pub(crate) name: Symbol, #[subdiagnostic] @@ -648,16 +679,16 @@ pub(crate) struct ParamInEnumDiscriminant { #[derive(Debug)] #[derive(Subdiagnostic)] pub(crate) enum ParamKindInEnumDiscriminant { - #[note(resolve_type_param_in_enum_discriminant)] + #[note("type parameters may not be used in enum discriminant values")] Type, - #[note(resolve_const_param_in_enum_discriminant)] + #[note("const parameters may not be used in enum discriminant values")] Const, - #[note(resolve_lifetime_param_in_enum_discriminant)] + #[note("lifetime parameters may not be used in enum discriminant values")] Lifetime, } #[derive(Subdiagnostic)] -#[label(resolve_change_import_binding)] +#[label("you can use `as` to change the binding name of the import")] pub(crate) struct ChangeImportBinding { #[primary_span] pub(crate) span: Span, @@ -665,7 +696,7 @@ pub(crate) struct ChangeImportBinding { #[derive(Subdiagnostic)] #[suggestion( - resolve_change_import_binding, + "you can use `as` to change the binding name of the import", code = "{suggestion}", applicability = "maybe-incorrect" )] @@ -676,7 +707,7 @@ pub(crate) struct ChangeImportBindingSuggestion { } #[derive(Diagnostic)] -#[diag(resolve_imports_cannot_refer_to)] +#[diag("imports cannot refer to {$what}")] pub(crate) struct ImportsCannotReferTo<'a> { #[primary_span] pub(crate) span: Span, @@ -684,7 +715,7 @@ pub(crate) struct ImportsCannotReferTo<'a> { } #[derive(Diagnostic)] -#[diag(resolve_cannot_find_ident_in_this_scope)] +#[diag("cannot find {$expected} `{$ident}` in this scope")] pub(crate) struct CannotFindIdentInThisScope<'a> { #[primary_span] pub(crate) span: Span, @@ -693,7 +724,7 @@ pub(crate) struct CannotFindIdentInThisScope<'a> { } #[derive(Subdiagnostic)] -#[note(resolve_explicit_unsafe_traits)] +#[note("unsafe traits like `{$ident}` should be implemented explicitly")] pub(crate) struct ExplicitUnsafeTraits { #[primary_span] pub(crate) span: Span, @@ -701,14 +732,14 @@ pub(crate) struct ExplicitUnsafeTraits { } #[derive(Subdiagnostic)] -#[note(resolve_macro_defined_later)] +#[note("a macro with the same name exists, but it appears later")] pub(crate) struct MacroDefinedLater { #[primary_span] pub(crate) span: Span, } #[derive(Subdiagnostic)] -#[label(resolve_consider_move_macro_position)] +#[label("consider moving the definition of `{$ident}` before this call")] pub(crate) struct MacroSuggMovePosition { #[primary_span] pub(crate) span: Span, @@ -717,19 +748,19 @@ pub(crate) struct MacroSuggMovePosition { #[derive(Subdiagnostic)] pub(crate) enum MacroRulesNot { - #[label(resolve_macro_cannot_use_as_fn_like)] + #[label("`{$ident}` exists, but has no rules for function-like invocation")] Func { #[primary_span] span: Span, ident: Ident, }, - #[label(resolve_macro_cannot_use_as_attr)] + #[label("`{$ident}` exists, but has no `attr` rules")] Attr { #[primary_span] span: Span, ident: Ident, }, - #[label(resolve_macro_cannot_use_as_derive)] + #[label("`{$ident}` exists, but has no `derive` rules")] Derive { #[primary_span] span: Span, @@ -738,22 +769,18 @@ pub(crate) enum MacroRulesNot { } #[derive(Subdiagnostic)] -#[note(resolve_missing_macro_rules_name)] +#[note("maybe you have forgotten to define a name for this `macro_rules!`")] pub(crate) struct MaybeMissingMacroRulesName { #[primary_span] pub(crate) spans: MultiSpan, } #[derive(Subdiagnostic)] -#[help(resolve_added_macro_use)] +#[help("have you added the `#[macro_use]` on the module/import?")] pub(crate) struct AddedMacroUse; #[derive(Subdiagnostic)] -#[suggestion( - resolve_consider_adding_a_derive, - code = "{suggestion}", - applicability = "maybe-incorrect" -)] +#[suggestion("consider adding a derive", code = "{suggestion}", applicability = "maybe-incorrect")] pub(crate) struct ConsiderAddingADerive { #[primary_span] pub(crate) span: Span, @@ -761,15 +788,15 @@ pub(crate) struct ConsiderAddingADerive { } #[derive(Diagnostic)] -#[diag(resolve_cannot_determine_import_resolution)] +#[diag("cannot determine resolution for the import")] pub(crate) struct CannotDetermineImportResolution { #[primary_span] pub(crate) span: Span, } #[derive(Diagnostic)] -#[diag(resolve_cannot_determine_macro_resolution)] -#[note] +#[diag("cannot determine resolution for the {$kind} `{$path}`")] +#[note("import resolution is stuck, try simplifying macro imports")] pub(crate) struct CannotDetermineMacroResolution { #[primary_span] pub(crate) span: Span, @@ -778,7 +805,7 @@ pub(crate) struct CannotDetermineMacroResolution { } #[derive(Diagnostic)] -#[diag(resolve_cannot_be_reexported_private, code = E0364)] +#[diag("`{$ident}` is private, and cannot be re-exported", code = E0364)] pub(crate) struct CannotBeReexportedPrivate { #[primary_span] pub(crate) span: Span, @@ -786,7 +813,7 @@ pub(crate) struct CannotBeReexportedPrivate { } #[derive(Diagnostic)] -#[diag(resolve_cannot_be_reexported_crate_public, code = E0364)] +#[diag("`{$ident}` is only public within the crate, and cannot be re-exported outside", code = E0364)] pub(crate) struct CannotBeReexportedCratePublic { #[primary_span] pub(crate) span: Span, @@ -794,35 +821,40 @@ pub(crate) struct CannotBeReexportedCratePublic { } #[derive(Diagnostic)] -#[diag(resolve_cannot_be_reexported_private, code = E0365)] -#[note(resolve_consider_declaring_with_pub)] +#[diag("`{$ident}` is private, and cannot be re-exported", code = E0365)] +#[note("consider declaring type or module `{$ident}` with `pub`")] pub(crate) struct CannotBeReexportedPrivateNS { #[primary_span] - #[label(resolve_reexport_of_private)] + #[label("re-export of private `{$ident}`")] pub(crate) span: Span, pub(crate) ident: Ident, } #[derive(Diagnostic)] -#[diag(resolve_cannot_be_reexported_crate_public, code = E0365)] -#[note(resolve_consider_declaring_with_pub)] +#[diag("`{$ident}` is only public within the crate, and cannot be re-exported outside", code = E0365)] +#[note("consider declaring type or module `{$ident}` with `pub`")] pub(crate) struct CannotBeReexportedCratePublicNS { #[primary_span] - #[label(resolve_reexport_of_crate_public)] + #[label("re-export of crate public `{$ident}`")] pub(crate) span: Span, pub(crate) ident: Ident, } #[derive(LintDiagnostic)] -#[diag(resolve_private_extern_crate_reexport, code = E0365)] +#[diag("extern crate `{$ident}` is private and cannot be re-exported", code = E0365)] pub(crate) struct PrivateExternCrateReexport { pub ident: Ident, - #[suggestion(code = "pub ", style = "verbose", applicability = "maybe-incorrect")] + #[suggestion( + "consider making the `extern crate` item publicly accessible", + code = "pub ", + style = "verbose", + applicability = "maybe-incorrect" + )] pub sugg: Span, } #[derive(Subdiagnostic)] -#[help(resolve_consider_adding_macro_export)] +#[help("consider adding a `#[macro_export]` to the macro in the imported module")] pub(crate) struct ConsiderAddingMacroExport { #[primary_span] pub(crate) span: Span, @@ -830,7 +862,7 @@ pub(crate) struct ConsiderAddingMacroExport { #[derive(Subdiagnostic)] #[suggestion( - resolve_consider_marking_as_pub_crate, + "in case you want to use the macro within this crate only, reduce the visibility to `pub(crate)`", code = "pub(crate)", applicability = "maybe-incorrect" )] @@ -840,7 +872,7 @@ pub(crate) struct ConsiderMarkingAsPubCrate { } #[derive(Subdiagnostic)] -#[note(resolve_consider_marking_as_pub)] +#[note("consider marking `{$ident}` as `pub` in the imported module")] pub(crate) struct ConsiderMarkingAsPub { #[primary_span] pub(crate) span: Span, @@ -848,7 +880,7 @@ pub(crate) struct ConsiderMarkingAsPub { } #[derive(Diagnostic)] -#[diag(resolve_cannot_glob_import_possible_crates)] +#[diag("cannot glob-import all possible crates")] pub(crate) struct CannotGlobImportAllCrates { #[primary_span] pub(crate) span: Span, @@ -856,7 +888,7 @@ pub(crate) struct CannotGlobImportAllCrates { #[derive(Subdiagnostic)] #[suggestion( - resolve_unexpected_res_change_ty_to_const_param_sugg, + "you might have meant to write a const parameter here", code = "const ", style = "verbose" )] @@ -869,7 +901,7 @@ pub(crate) struct UnexpectedResChangeTyToConstParamSugg { #[derive(Subdiagnostic)] #[multipart_suggestion( - resolve_unexpected_res_change_ty_to_const_param_sugg, + "you might have meant to write a const parameter here", applicability = "has-placeholders", style = "verbose" )] @@ -882,7 +914,7 @@ pub(crate) struct UnexpectedResChangeTyParamToConstParamSugg { #[derive(Subdiagnostic)] #[suggestion( - resolve_unexpected_res_use_at_op_in_slice_pat_with_range_sugg, + "if you meant to collect the rest of the slice in `{$ident}`, use the at operator", code = "{snippet}", applicability = "maybe-incorrect", style = "verbose" @@ -895,23 +927,27 @@ pub(crate) struct UnexpectedResUseAtOpInSlicePatWithRangeSugg { } #[derive(Diagnostic)] -#[diag(resolve_extern_crate_loading_macro_not_at_crate_root, code = E0468)] +#[diag("an `extern crate` loading macros must be at the crate root", code = E0468)] pub(crate) struct ExternCrateLoadingMacroNotAtCrateRoot { #[primary_span] pub(crate) span: Span, } #[derive(Diagnostic)] -#[diag(resolve_extern_crate_self_requires_renaming)] +#[diag("`extern crate self;` requires renaming")] pub(crate) struct ExternCrateSelfRequiresRenaming { #[primary_span] - #[suggestion(code = "extern crate self as name;", applicability = "has-placeholders")] + #[suggestion( + "rename the `self` crate to be able to import it", + code = "extern crate self as name;", + applicability = "has-placeholders" + )] pub(crate) span: Span, } #[derive(Diagnostic)] -#[diag(resolve_macro_use_name_already_in_use)] -#[note] +#[diag("`{$name}` is already in scope")] +#[note("macro-expanded `#[macro_use]`s may not shadow existing macros (see RFC 1560)")] pub(crate) struct MacroUseNameAlreadyInUse { #[primary_span] pub(crate) span: Span, @@ -919,74 +955,80 @@ pub(crate) struct MacroUseNameAlreadyInUse { } #[derive(Diagnostic)] -#[diag(resolve_imported_macro_not_found, code = E0469)] +#[diag("imported macro not found", code = E0469)] pub(crate) struct ImportedMacroNotFound { #[primary_span] pub(crate) span: Span, } #[derive(Diagnostic)] -#[diag(resolve_macro_extern_deprecated)] +#[diag("`#[macro_escape]` is a deprecated synonym for `#[macro_use]`")] pub(crate) struct MacroExternDeprecated { #[primary_span] pub(crate) span: Span, - #[help] + #[help("try an outer attribute: `#[macro_use]`")] pub inner_attribute: bool, } #[derive(Diagnostic)] -#[diag(resolve_arguments_macro_use_not_allowed)] +#[diag("arguments to `macro_use` are not allowed here")] pub(crate) struct ArgumentsMacroUseNotAllowed { #[primary_span] pub(crate) span: Span, } #[derive(Diagnostic)] -#[diag(resolve_unnamed_crate_root_import)] +#[diag("crate root imports need to be explicitly named: `use crate as name;`")] pub(crate) struct UnnamedCrateRootImport { #[primary_span] pub(crate) span: Span, } #[derive(Diagnostic)] -#[diag(resolve_macro_expanded_extern_crate_cannot_shadow_extern_arguments)] +#[diag("macro-expanded `extern crate` items cannot shadow names passed with `--extern`")] pub(crate) struct MacroExpandedExternCrateCannotShadowExternArguments { #[primary_span] pub(crate) span: Span, } #[derive(Diagnostic)] -#[diag(resolve_elided_anonymous_lifetime_report_error, code = E0637)] +#[diag("`&` without an explicit lifetime name cannot be used here", code = E0637)] pub(crate) struct ElidedAnonymousLifetimeReportError { #[primary_span] - #[label] + #[label("explicit lifetime name needed here")] pub(crate) span: Span, #[subdiagnostic] pub(crate) suggestion: Option, } #[derive(Diagnostic)] -#[diag(resolve_lending_iterator_report_error)] +#[diag( + "associated type `Iterator::Item` is declared without lifetime parameters, so using a borrowed type for them requires that lifetime to come from the implemented type" +)] pub(crate) struct LendingIteratorReportError { #[primary_span] pub(crate) lifetime: Span, - #[note] + #[note( + "you can't create an `Iterator` that borrows each `Item` from itself, but you can instead create a new type that borrows your existing type and implement `Iterator` for that new type" + )] pub(crate) ty: Span, } #[derive(Diagnostic)] -#[diag(resolve_anonymous_lifetime_non_gat_report_error)] +#[diag("missing lifetime in associated type")] pub(crate) struct AnonymousLifetimeNonGatReportError { #[primary_span] - #[label] + #[label("this lifetime must come from the implemented type")] pub(crate) lifetime: Span, - #[note] + #[note( + "in the trait the associated type is declared without lifetime parameters, so using a borrowed type for them requires that lifetime to come from the implemented type" + )] pub(crate) decl: MultiSpan, } #[derive(Subdiagnostic)] #[multipart_suggestion( - resolve_elided_anonymous_lifetime_report_error_suggestion, + "consider introducing a higher-ranked lifetime here", applicability = "machine-applicable" )] pub(crate) struct ElidedAnonymousLifetimeReportErrorSuggestion { @@ -997,15 +1039,15 @@ pub(crate) struct ElidedAnonymousLifetimeReportErrorSuggestion { } #[derive(Diagnostic)] -#[diag(resolve_explicit_anonymous_lifetime_report_error, code = E0637)] +#[diag("`'_` cannot be used here", code = E0637)] pub(crate) struct ExplicitAnonymousLifetimeReportError { #[primary_span] - #[label] + #[label("`'_` is a reserved lifetime name")] pub(crate) span: Span, } #[derive(Diagnostic)] -#[diag(resolve_implicit_elided_lifetimes_not_allowed_here, code = E0726)] +#[diag("implicit elided lifetime not allowed here", code = E0726)] pub(crate) struct ImplicitElidedLifetimeNotAllowedHere { #[primary_span] pub(crate) span: Span, @@ -1014,25 +1056,25 @@ pub(crate) struct ImplicitElidedLifetimeNotAllowedHere { } #[derive(Diagnostic)] -#[diag(resolve_underscore_lifetime_is_reserved, code = E0637)] -#[help] +#[diag("`'_` cannot be used here", code = E0637)] +#[help("use another lifetime specifier")] pub(crate) struct UnderscoreLifetimeIsReserved { #[primary_span] - #[label] + #[label("`'_` is a reserved lifetime name")] pub(crate) span: Span, } #[derive(Diagnostic)] -#[diag(resolve_static_lifetime_is_reserved, code = E0262)] +#[diag("invalid lifetime parameter name: `{$lifetime}`", code = E0262)] pub(crate) struct StaticLifetimeIsReserved { #[primary_span] - #[label] + #[label("'static is a reserved lifetime name")] pub(crate) span: Span, pub(crate) lifetime: Ident, } #[derive(Diagnostic)] -#[diag(resolve_variable_is_not_bound_in_all_patterns, code = E0408)] +#[diag("variable `{$name}` is not bound in all patterns", code = E0408)] pub(crate) struct VariableIsNotBoundInAllPatterns { #[primary_span] pub(crate) multispan: MultiSpan, @@ -1040,7 +1082,7 @@ pub(crate) struct VariableIsNotBoundInAllPatterns { } #[derive(Subdiagnostic, Debug, Clone)] -#[label(resolve_pattern_doesnt_bind_name)] +#[label("pattern doesn't bind `{$name}`")] pub(crate) struct PatternDoesntBindName { #[primary_span] pub(crate) span: Span, @@ -1048,7 +1090,7 @@ pub(crate) struct PatternDoesntBindName { } #[derive(Subdiagnostic, Debug, Clone)] -#[label(resolve_variable_not_in_all_patterns)] +#[label("variable not in all patterns")] pub(crate) struct VariableNotInAllPatterns { #[primary_span] pub(crate) span: Span, @@ -1056,7 +1098,7 @@ pub(crate) struct VariableNotInAllPatterns { #[derive(Subdiagnostic)] #[multipart_suggestion( - resolve_variable_is_a_typo, + "you might have meant to use the similarly named previously used binding `{$typo}`", applicability = "maybe-incorrect", style = "verbose" )] @@ -1067,8 +1109,8 @@ pub(crate) struct PatternBindingTypo { } #[derive(Diagnostic)] -#[diag(resolve_name_defined_multiple_time)] -#[note] +#[diag("the name `{$name}` is defined multiple times")] +#[note("`{$name}` must be defined only once in the {$descr} namespace of this {$container}")] pub(crate) struct NameDefinedMultipleTime { #[primary_span] pub(crate) span: Span, @@ -1083,12 +1125,12 @@ pub(crate) struct NameDefinedMultipleTime { #[derive(Subdiagnostic)] pub(crate) enum NameDefinedMultipleTimeLabel { - #[label(resolve_name_defined_multiple_time_reimported)] + #[label("`{$name}` reimported here")] Reimported { #[primary_span] span: Span, }, - #[label(resolve_name_defined_multiple_time_redefined)] + #[label("`{$name}` redefined here")] Redefined { #[primary_span] span: Span, @@ -1097,13 +1139,13 @@ pub(crate) enum NameDefinedMultipleTimeLabel { #[derive(Subdiagnostic)] pub(crate) enum NameDefinedMultipleTimeOldBindingLabel { - #[label(resolve_name_defined_multiple_time_old_binding_import)] + #[label("previous import of the {$old_kind} `{$name}` here")] Import { #[primary_span] span: Span, old_kind: &'static str, }, - #[label(resolve_name_defined_multiple_time_old_binding_definition)] + #[label("previous definition of the {$old_kind} `{$name}` here")] Definition { #[primary_span] span: Span, @@ -1112,42 +1154,42 @@ pub(crate) enum NameDefinedMultipleTimeOldBindingLabel { } #[derive(Diagnostic)] -#[diag(resolve_is_private, code = E0603)] +#[diag("{$ident_descr} `{$ident}` is private", code = E0603)] pub(crate) struct IsPrivate<'a> { #[primary_span] - #[label] + #[label("private {$ident_descr}")] pub(crate) span: Span, pub(crate) ident_descr: &'a str, pub(crate) ident: Ident, } #[derive(Diagnostic)] -#[diag(resolve_generic_arguments_in_macro_path)] +#[diag("generic arguments in macro path")] pub(crate) struct GenericArgumentsInMacroPath { #[primary_span] pub(crate) span: Span, } #[derive(Diagnostic)] -#[diag(resolve_attributes_starting_with_rustc_are_reserved)] +#[diag("attributes starting with `rustc` are reserved for use by the `rustc` compiler")] pub(crate) struct AttributesStartingWithRustcAreReserved { #[primary_span] pub(crate) span: Span, } #[derive(Diagnostic)] -#[diag(resolve_cannot_use_through_an_import)] +#[diag("cannot use {$article} {$descr} through an import")] pub(crate) struct CannotUseThroughAnImport { #[primary_span] pub(crate) span: Span, pub(crate) article: &'static str, pub(crate) descr: &'static str, - #[note] + #[note("the {$descr} imported here")] pub(crate) binding_span: Option, } #[derive(Diagnostic)] -#[diag(resolve_name_reserved_in_attribute_namespace)] +#[diag("name `{$ident}` is reserved in attribute namespace")] pub(crate) struct NameReservedInAttributeNamespace { #[primary_span] pub(crate) span: Span, @@ -1155,7 +1197,7 @@ pub(crate) struct NameReservedInAttributeNamespace { } #[derive(Diagnostic)] -#[diag(resolve_cannot_find_builtin_macro_with_name)] +#[diag("cannot find a built-in macro with name `{$ident}`")] pub(crate) struct CannotFindBuiltinMacroWithName { #[primary_span] pub(crate) span: Span, @@ -1163,34 +1205,34 @@ pub(crate) struct CannotFindBuiltinMacroWithName { } #[derive(Diagnostic)] -#[diag(resolve_tool_was_already_registered)] +#[diag("tool `{$tool}` was already registered")] pub(crate) struct ToolWasAlreadyRegistered { #[primary_span] pub(crate) span: Span, pub(crate) tool: Ident, - #[label] + #[label("already registered here")] pub(crate) old_ident_span: Span, } #[derive(Diagnostic)] -#[diag(resolve_tool_only_accepts_identifiers)] +#[diag("`{$tool}` only accepts identifiers")] pub(crate) struct ToolOnlyAcceptsIdentifiers { #[primary_span] - #[label] + #[label("not an identifier")] pub(crate) span: Span, pub(crate) tool: Symbol, } #[derive(Subdiagnostic)] pub(crate) enum DefinedHere { - #[label(resolve_similarly_named_defined_here)] + #[label("similarly named {$candidate_descr} `{$candidate}` defined here")] SimilarlyNamed { #[primary_span] span: Span, candidate_descr: &'static str, candidate: Symbol, }, - #[label(resolve_single_item_defined_here)] + #[label("{$candidate_descr} `{$candidate}` defined here")] SingleItem { #[primary_span] span: Span, @@ -1200,7 +1242,7 @@ pub(crate) enum DefinedHere { } #[derive(Subdiagnostic)] -#[label(resolve_outer_ident_is_not_publicly_reexported)] +#[label("{$outer_ident_descr} `{$outer_ident}` is not publicly re-exported")] pub(crate) struct OuterIdentIsNotPubliclyReexported { #[primary_span] pub(crate) span: Span, @@ -1209,7 +1251,7 @@ pub(crate) struct OuterIdentIsNotPubliclyReexported { } #[derive(Subdiagnostic)] -#[label(resolve_constructor_private_if_any_field_private)] +#[label("a constructor is private if any of the fields is private")] pub(crate) struct ConstructorPrivateIfAnyFieldPrivate { #[primary_span] pub(crate) span: Span, @@ -1217,7 +1259,10 @@ pub(crate) struct ConstructorPrivateIfAnyFieldPrivate { #[derive(Subdiagnostic)] #[multipart_suggestion( - resolve_consider_making_the_field_public, + "{ $number_of_fields -> + [one] consider making the field publicly accessible + *[other] consider making the fields publicly accessible + }", applicability = "maybe-incorrect", style = "verbose" )] @@ -1230,7 +1275,7 @@ pub(crate) struct ConsiderMakingTheFieldPublic { #[derive(Subdiagnostic)] pub(crate) enum ImportIdent { #[suggestion( - resolve_suggestion_import_ident_through_reexport, + "import `{$ident}` through the re-export", code = "{path}", applicability = "machine-applicable", style = "verbose" @@ -1242,7 +1287,7 @@ pub(crate) enum ImportIdent { path: String, }, #[suggestion( - resolve_suggestion_import_ident_directly, + "import `{$ident}` directly", code = "{path}", applicability = "machine-applicable", style = "verbose" @@ -1256,7 +1301,18 @@ pub(crate) enum ImportIdent { } #[derive(Subdiagnostic)] -#[note(resolve_note_and_refers_to_the_item_defined_here)] +#[note( + "{$first -> + [true] {$dots -> + [true] the {$binding_descr} `{$binding_name}` is defined here... + *[false] the {$binding_descr} `{$binding_name}` is defined here + } + *[false] {$dots -> + [true] ...and refers to the {$binding_descr} `{$binding_name}` which is defined here... + *[false] ...and refers to the {$binding_descr} `{$binding_name}` which is defined here + } + }" +)] pub(crate) struct NoteAndRefersToTheItemDefinedHere<'a> { #[primary_span] pub(crate) span: MultiSpan, @@ -1267,7 +1323,7 @@ pub(crate) struct NoteAndRefersToTheItemDefinedHere<'a> { } #[derive(Subdiagnostic)] -#[suggestion(resolve_remove_unnecessary_import, code = "", applicability = "maybe-incorrect")] +#[suggestion("remove unnecessary import", code = "", applicability = "maybe-incorrect")] pub(crate) struct RemoveUnnecessaryImport { #[primary_span] pub(crate) span: Span, @@ -1275,7 +1331,7 @@ pub(crate) struct RemoveUnnecessaryImport { #[derive(Subdiagnostic)] #[suggestion( - resolve_remove_unnecessary_import, + "remove unnecessary import", code = "", applicability = "maybe-incorrect", style = "tool-only" @@ -1286,7 +1342,7 @@ pub(crate) struct ToolOnlyRemoveUnnecessaryImport { } #[derive(Subdiagnostic)] -#[note(resolve_ident_imported_here_but_it_is_desc)] +#[note("`{$imported_ident}` is imported here, but it is {$imported_ident_desc}")] pub(crate) struct IdentImporterHereButItIsDesc<'a> { #[primary_span] pub(crate) span: Span, @@ -1295,7 +1351,7 @@ pub(crate) struct IdentImporterHereButItIsDesc<'a> { } #[derive(Subdiagnostic)] -#[note(resolve_ident_in_scope_but_it_is_desc)] +#[note("`{$imported_ident}` is in scope, but it is {$imported_ident_desc}")] pub(crate) struct IdentInScopeButItIsDesc<'a> { pub(crate) imported_ident: Ident, pub(crate) imported_ident_desc: &'a str, @@ -1319,50 +1375,55 @@ impl Subdiagnostic for FoundItemConfigureOut { let key = "feature".into(); let value = feature.into_diag_arg(&mut None); let msg = diag.dcx.eagerly_translate_to_string( - fluent::resolve_item_was_behind_feature, + inline_fluent!("the item is gated behind the `{$feature}` feature"), [(&key, &value)].into_iter(), ); multispan.push_span_label(span, msg); } ItemWas::CfgOut { span } => { - multispan.push_span_label(span, fluent::resolve_item_was_cfg_out); + multispan.push_span_label(span, inline_fluent!("the item is gated here")); } } - diag.span_note(multispan, fluent::resolve_found_an_item_configured_out); + diag.span_note(multispan, inline_fluent!("found an item that was configured out")); } } #[derive(Diagnostic)] -#[diag(resolve_trait_impl_mismatch)] +#[diag("item `{$name}` is an associated {$kind}, which doesn't match its trait `{$trait_path}`")] pub(crate) struct TraitImplMismatch { #[primary_span] - #[label] + #[label("does not match trait")] pub(crate) span: Span, pub(crate) name: Ident, pub(crate) kind: &'static str, pub(crate) trait_path: String, - #[label(resolve_trait_impl_mismatch_label_item)] + #[label("item in trait")] pub(crate) trait_item_span: Span, } #[derive(LintDiagnostic)] -#[diag(resolve_legacy_derive_helpers)] +#[diag("derive helper attribute is used before it is introduced")] pub(crate) struct LegacyDeriveHelpers { - #[label] + #[label("the attribute is introduced here")] pub span: Span, } #[derive(LintDiagnostic)] -#[diag(resolve_unused_extern_crate)] +#[diag("unused extern crate")] pub(crate) struct UnusedExternCrate { - #[label] + #[label("unused")] pub span: Span, - #[suggestion(code = "", applicability = "machine-applicable", style = "verbose")] + #[suggestion( + "remove the unused `extern crate`", + code = "", + applicability = "machine-applicable", + style = "verbose" + )] pub removal_span: Span, } #[derive(LintDiagnostic)] -#[diag(resolve_reexport_private_dependency)] +#[diag("{$kind} `{$name}` from private dependency '{$krate}' is re-exported")] pub(crate) struct ReexportPrivateDependency { pub name: Symbol, pub kind: &'static str, @@ -1370,32 +1431,32 @@ pub(crate) struct ReexportPrivateDependency { } #[derive(LintDiagnostic)] -#[diag(resolve_unused_label)] +#[diag("unused label")] pub(crate) struct UnusedLabel; #[derive(LintDiagnostic)] -#[diag(resolve_unused_macro_use)] +#[diag("unused `#[macro_use]` import")] pub(crate) struct UnusedMacroUse; #[derive(LintDiagnostic)] -#[diag(resolve_macro_use_deprecated)] -#[help] +#[diag("applying the `#[macro_use]` attribute to an `extern crate` item is deprecated")] +#[help("remove it and import macros at use sites with a `use` item instead")] pub(crate) struct MacroUseDeprecated; #[derive(LintDiagnostic)] -#[diag(resolve_macro_is_private)] +#[diag("macro `{$ident}` is private")] pub(crate) struct MacroIsPrivate { pub ident: Ident, } #[derive(LintDiagnostic)] -#[diag(resolve_unused_macro_definition)] +#[diag("unused macro definition: `{$name}`")] pub(crate) struct UnusedMacroDefinition { pub name: Symbol, } #[derive(LintDiagnostic)] -#[diag(resolve_macro_rule_never_used)] +#[diag("rule #{$n} of macro `{$name}` is never used")] pub(crate) struct MacroRuleNeverUsed { pub n: usize, pub name: Symbol, @@ -1412,36 +1473,43 @@ impl<'a> LintDiagnostic<'a, ()> for UnstableFeature { } #[derive(LintDiagnostic)] -#[diag(resolve_extern_crate_not_idiomatic)] +#[diag("`extern crate` is not idiomatic in the new edition")] pub(crate) struct ExternCrateNotIdiomatic { - #[suggestion(style = "verbose", code = "{code}", applicability = "machine-applicable")] + #[suggestion( + "convert it to a `use`", + style = "verbose", + code = "{code}", + applicability = "machine-applicable" + )] pub span: Span, pub code: &'static str, } #[derive(LintDiagnostic)] -#[diag(resolve_out_of_scope_macro_calls)] -#[help] +#[diag("cannot find macro `{$path}` in the current scope when looking from {$location}")] +#[help("import `macro_rules` with `use` to make it callable above its definition")] pub(crate) struct OutOfScopeMacroCalls { - #[label] + #[label("not found from {$location}")] pub span: Span, pub path: String, pub location: String, } #[derive(LintDiagnostic)] -#[diag(resolve_redundant_import_visibility)] +#[diag( + "glob import doesn't reexport anything with visibility `{$import_vis}` because no imported item is public enough" +)] pub(crate) struct RedundantImportVisibility { - #[note] + #[note("the most public imported item is `{$max_vis}`")] pub span: Span, - #[help] + #[help("reduce the glob import's visibility or increase visibility of imported items")] pub help: (), pub import_vis: String, pub max_vis: String, } #[derive(LintDiagnostic)] -#[diag(resolve_unknown_diagnostic_attribute)] +#[diag("unknown diagnostic attribute")] pub(crate) struct UnknownDiagnosticAttribute { #[subdiagnostic] pub typo: Option, @@ -1449,7 +1517,7 @@ pub(crate) struct UnknownDiagnosticAttribute { #[derive(Subdiagnostic)] #[suggestion( - resolve_unknown_diagnostic_attribute_typo_sugg, + "an attribute with a similar name exists", style = "verbose", code = "{typo_name}", applicability = "machine-applicable" diff --git a/compiler/rustc_resolve/src/lib.rs b/compiler/rustc_resolve/src/lib.rs index 659b74b74df77..36ec173cc571f 100644 --- a/compiler/rustc_resolve/src/lib.rs +++ b/compiler/rustc_resolve/src/lib.rs @@ -98,8 +98,6 @@ pub use macros::registered_tools_ast; use crate::ref_mut::{CmCell, CmRefCell}; -rustc_fluent_macro::fluent_messages! { "../messages.ftl" } - #[derive(Copy, Clone, PartialEq, Debug)] enum Determinacy { Determined, diff --git a/compiler/rustc_span/src/def_id.rs b/compiler/rustc_span/src/def_id.rs index a0ccf8d7e7986..82d455ab54f0f 100644 --- a/compiler/rustc_span/src/def_id.rs +++ b/compiler/rustc_span/src/def_id.rs @@ -540,7 +540,7 @@ macro_rules! typed_def_id { } // N.B.: when adding new typed `DefId`s update the corresponding trait impls in -// `rustc_middle::dep_graph::def_node` for `DepNodeParams`. +// `rustc_middle::dep_graph::dep_node_key` for `DepNodeKey`. typed_def_id! { ModDefId, LocalModDefId } impl LocalModDefId { diff --git a/compiler/rustc_span/src/symbol.rs b/compiler/rustc_span/src/symbol.rs index c88dd0948b2a9..1915ff0380fda 100644 --- a/compiler/rustc_span/src/symbol.rs +++ b/compiler/rustc_span/src/symbol.rs @@ -577,6 +577,7 @@ symbols! { automatically_derived, available_externally, avr, + avr_target_feature, avx, avx10_target_feature, avx512_target_feature, @@ -1956,7 +1957,6 @@ symbols! { rustc_deprecated_safe_2024, rustc_diagnostic_item, rustc_diagnostic_macros, - rustc_dirty, rustc_do_not_const_check, rustc_doc_primitive, rustc_driver, diff --git a/compiler/rustc_target/src/target_features.rs b/compiler/rustc_target/src/target_features.rs index bc12e1eb97370..a8e9d2e9dcaab 100644 --- a/compiler/rustc_target/src/target_features.rs +++ b/compiler/rustc_target/src/target_features.rs @@ -898,6 +898,28 @@ static M68K_FEATURES: &[(&str, Stability, ImpliedFeatures)] = &[ // tidy-alphabetical-end ]; +static AVR_FEATURES: &[(&str, Stability, ImpliedFeatures)] = &[ + // tidy-alphabetical-start + ("addsubiw", Unstable(sym::avr_target_feature), &[]), + ("break", Unstable(sym::avr_target_feature), &[]), + ("eijmpcall", Unstable(sym::avr_target_feature), &[]), + ("elpm", Unstable(sym::avr_target_feature), &[]), + ("elpmx", Unstable(sym::avr_target_feature), &[]), + ("ijmpcall", Unstable(sym::avr_target_feature), &[]), + ("jmpcall", Unstable(sym::avr_target_feature), &[]), + ("lowbytefirst", Unstable(sym::avr_target_feature), &[]), + ("lpm", Unstable(sym::avr_target_feature), &[]), + ("lpmx", Unstable(sym::avr_target_feature), &[]), + ("movw", Unstable(sym::avr_target_feature), &[]), + ("mul", Unstable(sym::avr_target_feature), &[]), + ("rmw", Unstable(sym::avr_target_feature), &[]), + ("spm", Unstable(sym::avr_target_feature), &[]), + ("spmx", Unstable(sym::avr_target_feature), &[]), + ("sram", Forbidden { reason: "devices that have no SRAM are unsupported" }, &[]), + ("tinyencoding", Unstable(sym::avr_target_feature), &[]), + // tidy-alphabetical-end +]; + /// When rustdoc is running, provide a list of all known features so that all their respective /// primitives may be documented. /// @@ -919,6 +941,7 @@ pub fn all_rust_features() -> impl Iterator { .chain(IBMZ_FEATURES) .chain(SPARC_FEATURES) .chain(M68K_FEATURES) + .chain(AVR_FEATURES) .cloned() .map(|(f, s, _)| (f, s)) } @@ -996,12 +1019,8 @@ impl Target { Arch::S390x => IBMZ_FEATURES, Arch::Sparc | Arch::Sparc64 => SPARC_FEATURES, Arch::M68k => M68K_FEATURES, - Arch::AmdGpu - | Arch::Avr - | Arch::Msp430 - | Arch::SpirV - | Arch::Xtensa - | Arch::Other(_) => &[], + Arch::Avr => AVR_FEATURES, + Arch::AmdGpu | Arch::Msp430 | Arch::SpirV | Arch::Xtensa | Arch::Other(_) => &[], } } @@ -1023,11 +1042,11 @@ impl Target { MIPS_FEATURES_FOR_CORRECT_FIXED_LENGTH_VECTOR_ABI } Arch::AmdGpu => AMDGPU_FEATURES_FOR_CORRECT_FIXED_LENGTH_VECTOR_ABI, - Arch::Nvptx64 | Arch::Bpf | Arch::M68k => &[], // no vector ABI + Arch::Nvptx64 | Arch::Bpf | Arch::M68k | Arch::Avr => &[], // no vector ABI Arch::CSky => CSKY_FEATURES_FOR_CORRECT_FIXED_LENGTH_VECTOR_ABI, // FIXME: for some tier3 targets, we are overly cautious and always give warnings // when passing args in vector registers. - Arch::Avr | Arch::Msp430 | Arch::SpirV | Arch::Xtensa | Arch::Other(_) => &[], + Arch::Msp430 | Arch::SpirV | Arch::Xtensa | Arch::Other(_) => &[], } } @@ -1224,6 +1243,12 @@ impl Target { // because the vector and float registers overlap. FeatureConstraints { required: &[], incompatible: &["soft-float"] } } + Arch::Avr => { + // SRAM is minimum requirement for C/C++ in both avr-gcc and Clang, + // and backends of them only support assembly for devices have no SRAM. + // See the discussion in https://github.com/rust-lang/rust/pull/146900 for more. + FeatureConstraints { required: &["sram"], incompatible: &[] } + } _ => NOTHING, } } diff --git a/src/bootstrap/src/core/config/config.rs b/src/bootstrap/src/core/config/config.rs index 07405a0309fe5..61eef3c015928 100644 --- a/src/bootstrap/src/core/config/config.rs +++ b/src/bootstrap/src/core/config/config.rs @@ -1859,11 +1859,17 @@ impl Config { .get(&target) .and_then(|t| t.llvm_libunwind) .or(self.llvm_libunwind_default) - .unwrap_or(if target.contains("fuchsia") || target.contains("hexagon") { - LlvmLibunwind::InTree - } else { - LlvmLibunwind::No - }) + .unwrap_or( + if target.contains("fuchsia") + || (target.contains("hexagon") && !target.contains("qurt")) + { + // Fuchsia and Hexagon Linux use in-tree llvm-libunwind. + // Hexagon QuRT uses libc_eh from the Hexagon SDK instead. + LlvmLibunwind::InTree + } else { + LlvmLibunwind::No + }, + ) } pub fn split_debuginfo(&self, target: TargetSelection) -> SplitDebuginfo { diff --git a/src/doc/rustc/src/platform-support/avr-none.md b/src/doc/rustc/src/platform-support/avr-none.md index 5218f19adf3b8..36874387b8048 100644 --- a/src/doc/rustc/src/platform-support/avr-none.md +++ b/src/doc/rustc/src/platform-support/avr-none.md @@ -68,6 +68,8 @@ the possible variants: https://github.com/llvm/llvm-project/blob/093d4db2f3c874d4683fb01194b00dbb20e5c713/clang/lib/Basic/Targets/AVR.cpp#L32 +Note that devices that have no SRAM are not supported, same as when compiling C/C++ programs with avr-gcc or Clang. + ## Testing You can use [`simavr`](https://github.com/buserror/simavr) to emulate the diff --git a/src/librustdoc/lib.rs b/src/librustdoc/lib.rs index 137319ae0c069..21ac851e54863 100644 --- a/src/librustdoc/lib.rs +++ b/src/librustdoc/lib.rs @@ -71,7 +71,7 @@ extern crate tikv_jemalloc_sys as _; use std::env::{self, VarError}; use std::io::{self, IsTerminal}; use std::path::Path; -use std::process; +use std::process::ExitCode; use rustc_errors::DiagCtxtHandle; use rustc_hir::def_id::LOCAL_CRATE; @@ -126,7 +126,7 @@ mod visit; mod visit_ast; mod visit_lib; -pub fn main() { +pub fn main() -> ExitCode { let mut early_dcx = EarlyDiagCtxt::new(ErrorOutputType::default()); rustc_driver::install_ice_hook( @@ -164,11 +164,10 @@ pub fn main() { Err(error) => early_dcx.early_fatal(error.to_string()), } - let exit_code = rustc_driver::catch_with_exit_code(|| { + rustc_driver::catch_with_exit_code(|| { let at_args = rustc_driver::args::raw_args(&early_dcx); main_args(&mut early_dcx, &at_args); - }); - process::exit(exit_code); + }) } fn init_logging(early_dcx: &EarlyDiagCtxt) { diff --git a/src/tools/clippy/src/driver.rs b/src/tools/clippy/src/driver.rs index 7425da70df909..cf06f43e8d4a3 100644 --- a/src/tools/clippy/src/driver.rs +++ b/src/tools/clippy/src/driver.rs @@ -32,7 +32,7 @@ use std::env; use std::fs::read_to_string; use std::io::Write as _; use std::path::Path; -use std::process::exit; +use std::process::ExitCode; /// If a command-line option matches `find_arg`, then apply the predicate `pred` on its value. If /// true, then return it. The parameter is assumed to be either `--arg=value` or `--arg value`. @@ -182,15 +182,17 @@ impl rustc_driver::Callbacks for ClippyCallbacks { } } -fn display_help() { +fn display_help() -> ExitCode { if writeln!(&mut anstream::stdout().lock(), "{}", help_message()).is_err() { - exit(rustc_driver::EXIT_FAILURE); + ExitCode::FAILURE + } else { + ExitCode::SUCCESS } } const BUG_REPORT_URL: &str = "https://github.com/rust-lang/rust-clippy/issues/new?template=ice.yml"; -pub fn main() { +pub fn main() -> ExitCode { let early_dcx = EarlyDiagCtxt::new(ErrorOutputType::default()); rustc_driver::init_rustc_env_logger(&early_dcx); @@ -203,7 +205,7 @@ pub fn main() { dcx.handle().note(format!("Clippy version: {version_info}")); }); - exit(rustc_driver::catch_with_exit_code(move || { + rustc_driver::catch_with_exit_code(move || { let mut orig_args = rustc_driver::args::raw_args(&early_dcx); let has_sysroot_arg = |args: &mut [String]| -> bool { @@ -246,15 +248,15 @@ pub fn main() { pass_sysroot_env_if_given(&mut args, sys_root_env); rustc_driver::run_compiler(&args, &mut DefaultCallbacks); - return; + return ExitCode::SUCCESS; } if orig_args.iter().any(|a| a == "--version" || a == "-V") { let version_info = rustc_tools_util::get_version_info!(); - match writeln!(&mut anstream::stdout().lock(), "{version_info}") { - Ok(()) => exit(rustc_driver::EXIT_SUCCESS), - Err(_) => exit(rustc_driver::EXIT_FAILURE), + return match writeln!(&mut anstream::stdout().lock(), "{version_info}") { + Ok(()) => ExitCode::SUCCESS, + Err(_) => ExitCode::FAILURE, } } @@ -268,8 +270,7 @@ pub fn main() { } if !wrapper_mode && (orig_args.iter().any(|a| a == "--help" || a == "-h") || orig_args.len() == 1) { - display_help(); - exit(0); + return display_help(); } let mut args: Vec = orig_args.clone(); @@ -311,7 +312,8 @@ pub fn main() { } else { rustc_driver::run_compiler(&args, &mut RustcCallbacks { clippy_args_var }); } - })) + ExitCode::SUCCESS + }) } #[must_use] diff --git a/src/tools/compiletest/src/runtest/incremental.rs b/src/tools/compiletest/src/runtest/incremental.rs index 44eb80300c394..5e7698e24858b 100644 --- a/src/tools/compiletest/src/runtest/incremental.rs +++ b/src/tools/compiletest/src/runtest/incremental.rs @@ -21,7 +21,7 @@ impl TestCx<'_> { // - execute build/foo/bar.exe and save output // // FIXME -- use non-incremental mode as an oracle? That doesn't apply - // to #[rustc_dirty] and clean tests I guess + // to #[rustc_clean] tests I guess let revision = self.revision.expect("incremental tests require a list of revisions"); diff --git a/src/tools/miri/src/bin/miri.rs b/src/tools/miri/src/bin/miri.rs index b28d70f058827..14528759472c8 100644 --- a/src/tools/miri/src/bin/miri.rs +++ b/src/tools/miri/src/bin/miri.rs @@ -39,6 +39,7 @@ mod log; use std::env; use std::num::{NonZero, NonZeroI32}; use std::ops::Range; +use std::process::ExitCode; use std::rc::Rc; use std::str::FromStr; use std::sync::Once; @@ -404,7 +405,11 @@ fn run_compiler_and_exit( // Invoke compiler, catch any unwinding panics and handle return code. let exit_code = rustc_driver::catch_with_exit_code(move || rustc_driver::run_compiler(args, callbacks)); - exit(exit_code) + exit(if exit_code == ExitCode::SUCCESS { + rustc_driver::EXIT_SUCCESS + } else { + rustc_driver::EXIT_FAILURE + }) } /// Parses a comma separated list of `T` from the given string: @@ -434,7 +439,7 @@ fn parse_range(val: &str) -> Result, &'static str> { Ok(from..to) } -fn main() { +fn main() -> ExitCode { let early_dcx = EarlyDiagCtxt::new(ErrorOutputType::default()); // Snapshot a copy of the environment before `rustc` starts messing with it. @@ -449,9 +454,7 @@ fn main() { if crate_kind == "host" { // For host crates like proc macros and build scripts, we are an entirely normal rustc. // These eventually produce actual binaries and never run in Miri. - match rustc_driver::main() { - // Empty match proves this function will never return. - } + return rustc_driver::main(); } else if crate_kind != "target" { panic!("invalid `MIRI_BE_RUSTC` value: {crate_kind:?}") }; diff --git a/src/tools/rustdoc/main.rs b/src/tools/rustdoc/main.rs index d4099cafe5df0..a35bcf9f547cb 100644 --- a/src/tools/rustdoc/main.rs +++ b/src/tools/rustdoc/main.rs @@ -1,6 +1,8 @@ // We need this feature as it changes `dylib` linking behavior and allows us to link to `rustc_driver`. #![feature(rustc_private)] -fn main() { +use std::process::ExitCode; + +fn main() -> ExitCode { rustdoc::main() } diff --git a/tests/codegen-llvm/gpu_offload/gpu_host.rs b/tests/codegen-llvm/gpu_offload/gpu_host.rs index d0bc34ec66b20..e12d7c792ae72 100644 --- a/tests/codegen-llvm/gpu_offload/gpu_host.rs +++ b/tests/codegen-llvm/gpu_offload/gpu_host.rs @@ -55,9 +55,7 @@ pub fn _kernel_1(x: &mut [f32; 256]) { // CHECK-NEXT: %.offload_ptrs = alloca [1 x ptr], align 8 // CHECK-NEXT: %.offload_sizes = alloca [1 x i64], align 8 // CHECK-NEXT: %kernel_args = alloca %struct.__tgt_kernel_arguments, align 8 -// CHECK: %dummy = load volatile ptr, ptr @.offload_sizes.[[K]], align 8 -// CHECK-NEXT: %dummy1 = load volatile ptr, ptr @.offloading.entry.[[K]], align 8 -// CHECK-NEXT: call void @__tgt_init_all_rtls() +// CHECK: call void @__tgt_init_all_rtls() // CHECK-NEXT: store ptr %x, ptr %.offload_baseptrs, align 8 // CHECK-NEXT: store ptr %x, ptr %.offload_ptrs, align 8 // CHECK-NEXT: store i64 1024, ptr %.offload_sizes, align 8 diff --git a/tests/codegen-llvm/issues/matches-logical-or-141497.rs b/tests/codegen-llvm/issues/matches-logical-or-141497.rs index 348f62096a5f2..59869fd70012a 100644 --- a/tests/codegen-llvm/issues/matches-logical-or-141497.rs +++ b/tests/codegen-llvm/issues/matches-logical-or-141497.rs @@ -2,7 +2,7 @@ // `f == FrameType::Inter || f == FrameType::Switch`. //@ compile-flags: -Copt-level=3 -//@ min-llvm-version: 21 +//@ min-llvm-version: 23 #![crate_type = "lib"] @@ -18,8 +18,7 @@ pub enum FrameType { #[no_mangle] pub fn is_inter_or_switch(f: FrameType) -> bool { // CHECK-NEXT: start: - // CHECK-NEXT: and i8 - // CHECK-NEXT: icmp + // CHECK-NEXT: trunc i8 %{{.*}} to i1 // CHECK-NEXT: ret matches!(f, FrameType::Inter | FrameType::Switch) } diff --git a/tests/incremental/dirty_clean.rs b/tests/incremental/clean.rs similarity index 100% rename from tests/incremental/dirty_clean.rs rename to tests/incremental/clean.rs diff --git a/tests/incremental/unchecked_dirty_clean.rs b/tests/incremental/unchecked_clean.rs similarity index 100% rename from tests/incremental/unchecked_dirty_clean.rs rename to tests/incremental/unchecked_clean.rs diff --git a/tests/rustdoc-gui/globals.goml b/tests/rustdoc-gui/globals.goml deleted file mode 100644 index 7fd9c5bfb6f2f..0000000000000 --- a/tests/rustdoc-gui/globals.goml +++ /dev/null @@ -1,20 +0,0 @@ -// Make sure search stores its data in `window` -// It needs to use a global to avoid racing on search-index.js and search.js -// https://github.com/rust-lang/rust/pull/118961 -include: "utils.goml" - -// URL query -go-to: "file://" + |DOC_PATH| + "/test_docs/index.html?search=sa" -wait-for: "#search-tabs" -wait-for-window-property-false: {"searchIndex": null} - -// Form input -go-to: "file://" + |DOC_PATH| + "/test_docs/index.html" -call-function: ("perform-search", {"query": "Foo"}) -wait-for-window-property-false: {"searchIndex": null} - -// source sidebar -go-to: "file://" + |DOC_PATH| + "/src/test_docs/lib.rs.html" -click: "#sidebar-button" -wait-for: "#src-sidebar details" -assert-window-property: {"searchIndex": null} diff --git a/tests/ui-fulldeps/obtain-borrowck.rs b/tests/ui-fulldeps/obtain-borrowck.rs index ea2dab614ec16..46ed23b58ac94 100644 --- a/tests/ui-fulldeps/obtain-borrowck.rs +++ b/tests/ui-fulldeps/obtain-borrowck.rs @@ -28,6 +28,7 @@ extern crate rustc_session; use std::cell::RefCell; use std::collections::HashMap; +use std::process::ExitCode; use std::thread_local; use rustc_borrowck::consumers::{self, BodyWithBorrowckFacts, ConsumerOptions}; @@ -42,16 +43,15 @@ use rustc_middle::ty::TyCtxt; use rustc_middle::util::Providers; use rustc_session::Session; -fn main() { - let exit_code = rustc_driver::catch_with_exit_code(move || { +fn main() -> ExitCode { + rustc_driver::catch_with_exit_code(move || { let mut rustc_args: Vec<_> = std::env::args().collect(); // We must pass -Zpolonius so that the borrowck information is computed. rustc_args.push("-Zpolonius".to_owned()); let mut callbacks = CompilerCalls::default(); // Call the Rust compiler with our callbacks. rustc_driver::run_compiler(&rustc_args, &mut callbacks); - }); - std::process::exit(exit_code); + }) } #[derive(Default)] diff --git a/tests/ui/abi/avr-sram.disable_sram.stderr b/tests/ui/abi/avr-sram.disable_sram.stderr new file mode 100644 index 0000000000000..31b9084f73a48 --- /dev/null +++ b/tests/ui/abi/avr-sram.disable_sram.stderr @@ -0,0 +1,12 @@ +warning: target feature `sram` cannot be disabled with `-Ctarget-feature`: devices that have no SRAM are unsupported + | + = note: this was previously accepted by the compiler but is being phased out; it will become a hard error in a future release! + = note: for more information, see issue #116344 + +warning: target feature `sram` must be enabled to ensure that the ABI of the current target can be implemented correctly + | + = note: this was previously accepted by the compiler but is being phased out; it will become a hard error in a future release! + = note: for more information, see issue #116344 + +warning: 2 warnings emitted + diff --git a/tests/ui/abi/avr-sram.no_sram.stderr b/tests/ui/abi/avr-sram.no_sram.stderr new file mode 100644 index 0000000000000..3f74bf66f190d --- /dev/null +++ b/tests/ui/abi/avr-sram.no_sram.stderr @@ -0,0 +1,7 @@ +warning: target feature `sram` must be enabled to ensure that the ABI of the current target can be implemented correctly + | + = note: this was previously accepted by the compiler but is being phased out; it will become a hard error in a future release! + = note: for more information, see issue #116344 + +warning: 1 warning emitted + diff --git a/tests/ui/abi/avr-sram.rs b/tests/ui/abi/avr-sram.rs new file mode 100644 index 0000000000000..d768ad77c3ab5 --- /dev/null +++ b/tests/ui/abi/avr-sram.rs @@ -0,0 +1,19 @@ +//@ add-minicore +//@ revisions: has_sram no_sram disable_sram +//@ build-pass +//@[has_sram] compile-flags: --target avr-none -C target-cpu=atmega328p +//@[has_sram] needs-llvm-components: avr +//@[no_sram] compile-flags: --target avr-none -C target-cpu=attiny11 +//@[no_sram] needs-llvm-components: avr +//@[disable_sram] compile-flags: --target avr-none -C target-cpu=atmega328p -C target-feature=-sram +//@[disable_sram] needs-llvm-components: avr +//@ ignore-backends: gcc +//[no_sram,disable_sram]~? WARN target feature `sram` must be enabled +//[disable_sram]~? WARN target feature `sram` cannot be disabled with `-Ctarget-feature` + +#![feature(no_core)] +#![no_core] +#![crate_type = "lib"] + +extern crate minicore; +use minicore::*; diff --git a/tests/ui/check-cfg/target_feature.stderr b/tests/ui/check-cfg/target_feature.stderr index 89123c9100825..06a7f477a7fdf 100644 --- a/tests/ui/check-cfg/target_feature.stderr +++ b/tests/ui/check-cfg/target_feature.stderr @@ -14,6 +14,7 @@ LL | cfg!(target_feature = "_UNEXPECTED_VALUE"); `7e10` `a` `aclass` +`addsubiw` `adx` `aes` `altivec` @@ -57,6 +58,7 @@ LL | cfg!(target_feature = "_UNEXPECTED_VALUE"); `bf16` `bmi1` `bmi2` +`break` `bti` `bulk-memory` `c` @@ -83,6 +85,9 @@ LL | cfg!(target_feature = "_UNEXPECTED_VALUE"); `e2` `ecv` `edsp` +`eijmpcall` +`elpm` +`elpmx` `elrw` `enhanced-sort` `ermsb` @@ -148,6 +153,7 @@ LL | cfg!(target_feature = "_UNEXPECTED_VALUE"); `hvxv79` `hwdiv` `i8mm` +`ijmpcall` `isa-68000` `isa-68010` `isa-68020` @@ -156,6 +162,7 @@ LL | cfg!(target_feature = "_UNEXPECTED_VALUE"); `isa-68060` `isa-68881` `isa-68882` +`jmpcall` `jsconv` `kl` `lahfsahf` @@ -166,6 +173,9 @@ LL | cfg!(target_feature = "_UNEXPECTED_VALUE"); `ld-seq-sa` `leoncasa` `lor` +`lowbytefirst` +`lpm` +`lpmx` `lse` `lse128` `lse2` @@ -187,11 +197,13 @@ LL | cfg!(target_feature = "_UNEXPECTED_VALUE"); `mops` `movbe` `movrs` +`movw` `mp` `mp1e2` `msa` `msync` `mte` +`mul` `multivalue` `mutable-globals` `neon` @@ -256,6 +268,7 @@ LL | cfg!(target_feature = "_UNEXPECTED_VALUE"); `reference-types` `relax` `relaxed-simd` +`rmw` `rtm` `rva23u64` `sb` @@ -308,6 +321,8 @@ LL | cfg!(target_feature = "_UNEXPECTED_VALUE"); `sme2p1` `soft-float` `spe` +`spm` +`spmx` `ssbs` `sse` `sse2` @@ -332,6 +347,7 @@ LL | cfg!(target_feature = "_UNEXPECTED_VALUE"); `tbm` `thumb-mode` `thumb2` +`tinyencoding` `tme` `transactional-execution` `trust` diff --git a/tests/ui/dep-graph/dep-graph-assoc-type-codegen.stderr b/tests/ui/dep-graph/dep-graph-assoc-type-codegen.stderr index f26b43aa3ec74..b0372051f0264 100644 --- a/tests/ui/dep-graph/dep-graph-assoc-type-codegen.stderr +++ b/tests/ui/dep-graph/dep-graph-assoc-type-codegen.stderr @@ -1,8 +1,8 @@ error: OK - --> $DIR/dep-graph-assoc-type-codegen.rs:29:5 + --> $DIR/dep-graph-assoc-type-codegen.rs:29:34 | LL | #[rustc_then_this_would_need(typeck)] - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + | ^^^^^^ error: aborting due to 1 previous error diff --git a/tests/ui/dep-graph/dep-graph-caller-callee.stderr b/tests/ui/dep-graph/dep-graph-caller-callee.stderr index 4d06dc7f3ed37..33fe91b3500a6 100644 --- a/tests/ui/dep-graph/dep-graph-caller-callee.stderr +++ b/tests/ui/dep-graph/dep-graph-caller-callee.stderr @@ -1,14 +1,14 @@ error: OK - --> $DIR/dep-graph-caller-callee.rs:21:5 + --> $DIR/dep-graph-caller-callee.rs:21:34 | LL | #[rustc_then_this_would_need(typeck)] - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + | ^^^^^^ error: no path from `x` to `typeck` - --> $DIR/dep-graph-caller-callee.rs:32:5 + --> $DIR/dep-graph-caller-callee.rs:32:34 | LL | #[rustc_then_this_would_need(typeck)] - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + | ^^^^^^ error: aborting due to 2 previous errors diff --git a/tests/ui/dep-graph/dep-graph-check-attr.rs b/tests/ui/dep-graph/dep-graph-check-attr.rs index a45bf24f8c1ff..c0697a5316f7d 100644 --- a/tests/ui/dep-graph/dep-graph-check-attr.rs +++ b/tests/ui/dep-graph/dep-graph-check-attr.rs @@ -5,15 +5,15 @@ #![allow(dead_code)] #![allow(unused_variables)] -#[rustc_clean(hir_owner)] //~ ERROR attribute requires -Z query-dep-graph +#[rustc_clean(cfg = "foo")] //~ ERROR attribute requires -Z query-dep-graph fn main() {} -#[rustc_if_this_changed(hir_owner)] //~ ERROR attribute requires -Z query-dep-graph +#[rustc_if_this_changed] //~ ERROR attribute requires -Z query-dep-graph struct Foo { f: T, } -#[rustc_clean(hir_owner)] //~ ERROR attribute requires -Z query-dep-graph +#[rustc_clean(cfg = "foo")] //~ ERROR attribute requires -Z query-dep-graph type TypeAlias = Foo; #[rustc_then_this_would_need(variances_of)] //~ ERROR attribute requires -Z query-dep-graph diff --git a/tests/ui/dep-graph/dep-graph-check-attr.stderr b/tests/ui/dep-graph/dep-graph-check-attr.stderr index 46f4e4358cf6a..4b651c47ac83a 100644 --- a/tests/ui/dep-graph/dep-graph-check-attr.stderr +++ b/tests/ui/dep-graph/dep-graph-check-attr.stderr @@ -1,20 +1,20 @@ error: attribute requires -Z query-dep-graph to be enabled --> $DIR/dep-graph-check-attr.rs:8:1 | -LL | #[rustc_clean(hir_owner)] - | ^^^^^^^^^^^^^^^^^^^^^^^^^ +LL | #[rustc_clean(cfg = "foo")] + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^ error: attribute requires -Z query-dep-graph to be enabled --> $DIR/dep-graph-check-attr.rs:11:1 | -LL | #[rustc_if_this_changed(hir_owner)] - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +LL | #[rustc_if_this_changed] + | ^^^^^^^^^^^^^^^^^^^^^^^^ error: attribute requires -Z query-dep-graph to be enabled --> $DIR/dep-graph-check-attr.rs:16:1 | -LL | #[rustc_clean(hir_owner)] - | ^^^^^^^^^^^^^^^^^^^^^^^^^ +LL | #[rustc_clean(cfg = "foo")] + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^ error: attribute requires -Z query-dep-graph to be enabled --> $DIR/dep-graph-check-attr.rs:19:1 diff --git a/tests/ui/dep-graph/dep-graph-struct-signature.stderr b/tests/ui/dep-graph/dep-graph-struct-signature.stderr index cfe1e62d9318f..98efedc7244c8 100644 --- a/tests/ui/dep-graph/dep-graph-struct-signature.stderr +++ b/tests/ui/dep-graph/dep-graph-struct-signature.stderr @@ -1,134 +1,134 @@ error: no path from `WillChange` to `type_of` - --> $DIR/dep-graph-struct-signature.rs:28:5 + --> $DIR/dep-graph-struct-signature.rs:28:34 | LL | #[rustc_then_this_would_need(type_of)] - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + | ^^^^^^^ error: no path from `WillChange` to `associated_item` - --> $DIR/dep-graph-struct-signature.rs:29:5 + --> $DIR/dep-graph-struct-signature.rs:29:34 | LL | #[rustc_then_this_would_need(associated_item)] - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + | ^^^^^^^^^^^^^^^ error: no path from `WillChange` to `trait_def` - --> $DIR/dep-graph-struct-signature.rs:30:5 + --> $DIR/dep-graph-struct-signature.rs:30:34 | LL | #[rustc_then_this_would_need(trait_def)] - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + | ^^^^^^^^^ error: OK - --> $DIR/dep-graph-struct-signature.rs:36:5 + --> $DIR/dep-graph-struct-signature.rs:36:34 | LL | #[rustc_then_this_would_need(fn_sig)] - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + | ^^^^^^ error: OK - --> $DIR/dep-graph-struct-signature.rs:37:5 + --> $DIR/dep-graph-struct-signature.rs:37:34 | LL | #[rustc_then_this_would_need(typeck)] - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + | ^^^^^^ error: OK - --> $DIR/dep-graph-struct-signature.rs:40:5 + --> $DIR/dep-graph-struct-signature.rs:40:34 | LL | #[rustc_then_this_would_need(fn_sig)] - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + | ^^^^^^ error: OK - --> $DIR/dep-graph-struct-signature.rs:41:5 + --> $DIR/dep-graph-struct-signature.rs:41:34 | LL | #[rustc_then_this_would_need(typeck)] - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + | ^^^^^^ error: OK - --> $DIR/dep-graph-struct-signature.rs:46:5 + --> $DIR/dep-graph-struct-signature.rs:46:34 | LL | #[rustc_then_this_would_need(type_of)] - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + | ^^^^^^^ error: OK - --> $DIR/dep-graph-struct-signature.rs:53:5 + --> $DIR/dep-graph-struct-signature.rs:53:34 | LL | #[rustc_then_this_would_need(type_of)] - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + | ^^^^^^^ error: OK - --> $DIR/dep-graph-struct-signature.rs:61:9 + --> $DIR/dep-graph-struct-signature.rs:61:38 | LL | #[rustc_then_this_would_need(type_of)] - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + | ^^^^^^^ error: OK - --> $DIR/dep-graph-struct-signature.rs:63:9 + --> $DIR/dep-graph-struct-signature.rs:63:38 | LL | #[rustc_then_this_would_need(type_of)] - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + | ^^^^^^^ error: no path from `WillChange` to `type_of` - --> $DIR/dep-graph-struct-signature.rs:68:5 + --> $DIR/dep-graph-struct-signature.rs:68:34 | LL | #[rustc_then_this_would_need(type_of)] - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + | ^^^^^^^ error: no path from `WillChange` to `type_of` - --> $DIR/dep-graph-struct-signature.rs:75:5 + --> $DIR/dep-graph-struct-signature.rs:75:34 | LL | #[rustc_then_this_would_need(type_of)] - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + | ^^^^^^^ error: no path from `WillChange` to `fn_sig` - --> $DIR/dep-graph-struct-signature.rs:81:5 + --> $DIR/dep-graph-struct-signature.rs:81:34 | LL | #[rustc_then_this_would_need(fn_sig)] - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + | ^^^^^^ error: no path from `WillChange` to `fn_sig` - --> $DIR/dep-graph-struct-signature.rs:84:5 + --> $DIR/dep-graph-struct-signature.rs:84:34 | LL | #[rustc_then_this_would_need(fn_sig)] - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + | ^^^^^^ error: no path from `WillChange` to `typeck` - --> $DIR/dep-graph-struct-signature.rs:85:5 + --> $DIR/dep-graph-struct-signature.rs:85:34 | LL | #[rustc_then_this_would_need(typeck)] - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + | ^^^^^^ error: OK - --> $DIR/dep-graph-struct-signature.rs:32:9 + --> $DIR/dep-graph-struct-signature.rs:32:38 | LL | #[rustc_then_this_would_need(fn_sig)] - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + | ^^^^^^ error: no path from `WillChange` to `fn_sig` - --> $DIR/dep-graph-struct-signature.rs:77:9 + --> $DIR/dep-graph-struct-signature.rs:77:38 | LL | #[rustc_then_this_would_need(fn_sig)] - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + | ^^^^^^ error: OK - --> $DIR/dep-graph-struct-signature.rs:48:9 + --> $DIR/dep-graph-struct-signature.rs:48:38 | LL | #[rustc_then_this_would_need(fn_sig)] - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + | ^^^^^^ error: OK - --> $DIR/dep-graph-struct-signature.rs:49:9 + --> $DIR/dep-graph-struct-signature.rs:49:38 | LL | #[rustc_then_this_would_need(typeck)] - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + | ^^^^^^ error: OK - --> $DIR/dep-graph-struct-signature.rs:55:9 + --> $DIR/dep-graph-struct-signature.rs:55:38 | LL | #[rustc_then_this_would_need(fn_sig)] - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + | ^^^^^^ error: OK - --> $DIR/dep-graph-struct-signature.rs:56:9 + --> $DIR/dep-graph-struct-signature.rs:56:38 | LL | #[rustc_then_this_would_need(typeck)] - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + | ^^^^^^ error: aborting due to 22 previous errors diff --git a/tests/ui/dep-graph/dep-graph-trait-impl-two-traits-same-method.stderr b/tests/ui/dep-graph/dep-graph-trait-impl-two-traits-same-method.stderr index 6f56cbc8dd7ae..293f918a31875 100644 --- a/tests/ui/dep-graph/dep-graph-trait-impl-two-traits-same-method.stderr +++ b/tests/ui/dep-graph/dep-graph-trait-impl-two-traits-same-method.stderr @@ -1,14 +1,14 @@ error: OK - --> $DIR/dep-graph-trait-impl-two-traits-same-method.rs:33:5 + --> $DIR/dep-graph-trait-impl-two-traits-same-method.rs:33:34 | LL | #[rustc_then_this_would_need(typeck)] - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + | ^^^^^^ error: no path from `x::` to `typeck` - --> $DIR/dep-graph-trait-impl-two-traits-same-method.rs:42:5 + --> $DIR/dep-graph-trait-impl-two-traits-same-method.rs:42:34 | LL | #[rustc_then_this_would_need(typeck)] - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + | ^^^^^^ error: aborting due to 2 previous errors diff --git a/tests/ui/dep-graph/dep-graph-trait-impl-two-traits.stderr b/tests/ui/dep-graph/dep-graph-trait-impl-two-traits.stderr index 08f382cc024c7..46cb0e9ea86fa 100644 --- a/tests/ui/dep-graph/dep-graph-trait-impl-two-traits.stderr +++ b/tests/ui/dep-graph/dep-graph-trait-impl-two-traits.stderr @@ -1,14 +1,14 @@ error: no path from `x::` to `typeck` - --> $DIR/dep-graph-trait-impl-two-traits.rs:32:5 + --> $DIR/dep-graph-trait-impl-two-traits.rs:32:34 | LL | #[rustc_then_this_would_need(typeck)] - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + | ^^^^^^ error: no path from `x::` to `typeck` - --> $DIR/dep-graph-trait-impl-two-traits.rs:41:5 + --> $DIR/dep-graph-trait-impl-two-traits.rs:41:34 | LL | #[rustc_then_this_would_need(typeck)] - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + | ^^^^^^ error: aborting due to 2 previous errors diff --git a/tests/ui/dep-graph/dep-graph-trait-impl.stderr b/tests/ui/dep-graph/dep-graph-trait-impl.stderr index bfee6d5c87b34..a5fce64c3a1c4 100644 --- a/tests/ui/dep-graph/dep-graph-trait-impl.stderr +++ b/tests/ui/dep-graph/dep-graph-trait-impl.stderr @@ -1,32 +1,32 @@ error: OK - --> $DIR/dep-graph-trait-impl.rs:28:5 + --> $DIR/dep-graph-trait-impl.rs:28:34 | LL | #[rustc_then_this_would_need(typeck)] - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + | ^^^^^^ error: OK - --> $DIR/dep-graph-trait-impl.rs:33:5 + --> $DIR/dep-graph-trait-impl.rs:33:34 | LL | #[rustc_then_this_would_need(typeck)] - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + | ^^^^^^ error: OK - --> $DIR/dep-graph-trait-impl.rs:38:5 + --> $DIR/dep-graph-trait-impl.rs:38:34 | LL | #[rustc_then_this_would_need(typeck)] - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + | ^^^^^^ error: OK - --> $DIR/dep-graph-trait-impl.rs:43:5 + --> $DIR/dep-graph-trait-impl.rs:43:34 | LL | #[rustc_then_this_would_need(typeck)] - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + | ^^^^^^ error: no path from `x::` to `typeck` - --> $DIR/dep-graph-trait-impl.rs:56:5 + --> $DIR/dep-graph-trait-impl.rs:56:34 | LL | #[rustc_then_this_would_need(typeck)] - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + | ^^^^^^ error: aborting due to 5 previous errors diff --git a/tests/ui/dep-graph/dep-graph-type-alias.stderr b/tests/ui/dep-graph/dep-graph-type-alias.stderr index 42ac803b22ece..9f24c1113b982 100644 --- a/tests/ui/dep-graph/dep-graph-type-alias.stderr +++ b/tests/ui/dep-graph/dep-graph-type-alias.stderr @@ -1,74 +1,74 @@ error: no path from `TypeAlias` to `type_of` - --> $DIR/dep-graph-type-alias.rs:18:1 + --> $DIR/dep-graph-type-alias.rs:18:30 | LL | #[rustc_then_this_would_need(type_of)] - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + | ^^^^^^^ error: OK - --> $DIR/dep-graph-type-alias.rs:20:5 + --> $DIR/dep-graph-type-alias.rs:20:34 | LL | #[rustc_then_this_would_need(type_of)] - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + | ^^^^^^^ error: no path from `TypeAlias` to `type_of` - --> $DIR/dep-graph-type-alias.rs:25:1 + --> $DIR/dep-graph-type-alias.rs:25:30 | LL | #[rustc_then_this_would_need(type_of)] - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + | ^^^^^^^ error: OK - --> $DIR/dep-graph-type-alias.rs:28:9 + --> $DIR/dep-graph-type-alias.rs:28:38 | LL | #[rustc_then_this_would_need(type_of)] - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + | ^^^^^^^ error: no path from `TypeAlias` to `type_of` - --> $DIR/dep-graph-type-alias.rs:34:1 + --> $DIR/dep-graph-type-alias.rs:34:30 | LL | #[rustc_then_this_would_need(type_of)] - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + | ^^^^^^^ error: no path from `TypeAlias` to `type_of` - --> $DIR/dep-graph-type-alias.rs:42:1 + --> $DIR/dep-graph-type-alias.rs:42:30 | LL | #[rustc_then_this_would_need(type_of)] - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + | ^^^^^^^ error: OK - --> $DIR/dep-graph-type-alias.rs:49:1 + --> $DIR/dep-graph-type-alias.rs:49:30 | LL | #[rustc_then_this_would_need(type_of)] - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + | ^^^^^^^ error: OK - --> $DIR/dep-graph-type-alias.rs:52:1 + --> $DIR/dep-graph-type-alias.rs:52:30 | LL | #[rustc_then_this_would_need(fn_sig)] - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + | ^^^^^^ error: OK - --> $DIR/dep-graph-type-alias.rs:53:1 + --> $DIR/dep-graph-type-alias.rs:53:30 | LL | #[rustc_then_this_would_need(typeck)] - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + | ^^^^^^ error: OK - --> $DIR/dep-graph-type-alias.rs:36:5 + --> $DIR/dep-graph-type-alias.rs:36:34 | LL | #[rustc_then_this_would_need(fn_sig)] - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + | ^^^^^^ error: OK - --> $DIR/dep-graph-type-alias.rs:44:5 + --> $DIR/dep-graph-type-alias.rs:44:34 | LL | #[rustc_then_this_would_need(fn_sig)] - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + | ^^^^^^ error: OK - --> $DIR/dep-graph-type-alias.rs:45:5 + --> $DIR/dep-graph-type-alias.rs:45:34 | LL | #[rustc_then_this_would_need(typeck)] - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + | ^^^^^^ error: aborting due to 12 previous errors diff --git a/tests/ui/dep-graph/dep-graph-variance-alias.stderr b/tests/ui/dep-graph/dep-graph-variance-alias.stderr index e11de2452899f..83ef573aad484 100644 --- a/tests/ui/dep-graph/dep-graph-variance-alias.stderr +++ b/tests/ui/dep-graph/dep-graph-variance-alias.stderr @@ -1,8 +1,8 @@ error: OK - --> $DIR/dep-graph-variance-alias.rs:19:1 + --> $DIR/dep-graph-variance-alias.rs:19:30 | LL | #[rustc_then_this_would_need(variances_of)] - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + | ^^^^^^^^^^^^ error: aborting due to 1 previous error diff --git a/tests/ui/feature-gates/issue-43106-gating-of-builtin-attrs.rs b/tests/ui/feature-gates/issue-43106-gating-of-builtin-attrs.rs index 9695a73c137f6..83debd17777ae 100644 --- a/tests/ui/feature-gates/issue-43106-gating-of-builtin-attrs.rs +++ b/tests/ui/feature-gates/issue-43106-gating-of-builtin-attrs.rs @@ -467,26 +467,26 @@ mod no_implicit_prelude { #[reexport_test_harness_main = "2900"] //~^ WARN crate-level attribute should be -//~| HELP add a `!` mod reexport_test_harness_main { +//~^ NOTE this attribute does not have an `!`, which means it is applied to this module mod inner { #![reexport_test_harness_main="2900"] } - //~^ WARN crate-level attribute should be + //~^ WARN the `#![reexport_test_harness_main]` attribute can only be used at the crate root #[reexport_test_harness_main = "2900"] fn f() { } //~^ WARN crate-level attribute should be - //~| HELP add a `!` + //~| NOTE this attribute does not have an `!`, which means it is applied to this function #[reexport_test_harness_main = "2900"] struct S; //~^ WARN crate-level attribute should be - //~| HELP add a `!` + //~| NOTE this attribute does not have an `!`, which means it is applied to this struct #[reexport_test_harness_main = "2900"] type T = S; //~^ WARN crate-level attribute should be - //~| HELP add a `!` + //~| NOTE this attribute does not have an `!`, which means it is applied to this type alias #[reexport_test_harness_main = "2900"] impl S { } //~^ WARN crate-level attribute should be - //~| HELP add a `!` + //~| NOTE this attribute does not have an `!`, which means it is applied to this implementation block } // Cannot feed "2700" to `#[macro_escape]` without signaling an error. diff --git a/tests/ui/feature-gates/issue-43106-gating-of-builtin-attrs.stderr b/tests/ui/feature-gates/issue-43106-gating-of-builtin-attrs.stderr index d69daf45b3524..482980dde3bf5 100644 --- a/tests/ui/feature-gates/issue-43106-gating-of-builtin-attrs.stderr +++ b/tests/ui/feature-gates/issue-43106-gating-of-builtin-attrs.stderr @@ -186,22 +186,6 @@ warning: unknown lint: `x5100` LL | #[deny(x5100)] impl S { } | ^^^^^ -warning: crate-level attribute should be an inner attribute - --> $DIR/issue-43106-gating-of-builtin-attrs.rs:468:1 - | -LL | #[reexport_test_harness_main = "2900"] - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ - | -note: the lint level is defined here - --> $DIR/issue-43106-gating-of-builtin-attrs.rs:36:9 - | -LL | #![warn(unused_attributes, unknown_lints)] - | ^^^^^^^^^^^^^^^^^ -help: add a `!` - | -LL | #![reexport_test_harness_main = "2900"] - | + - warning: attribute should be applied to an `extern` block with non-Rust ABI --> $DIR/issue-43106-gating-of-builtin-attrs.rs:710:1 | @@ -217,6 +201,11 @@ LL | | } | |_- not an `extern` block | = warning: this was previously accepted by the compiler but is being phased out; it will become a hard error in a future release! +note: the lint level is defined here + --> $DIR/issue-43106-gating-of-builtin-attrs.rs:36:9 + | +LL | #![warn(unused_attributes, unknown_lints)] + | ^^^^^^^^^^^^^^^^^ warning: crate-level attribute should be an inner attribute --> $DIR/issue-43106-gating-of-builtin-attrs.rs:860:1 @@ -245,56 +234,6 @@ LL | #![feature(rust1)] | = note: `#[warn(stable_features)]` on by default -warning: crate-level attribute should be in the root module - --> $DIR/issue-43106-gating-of-builtin-attrs.rs:472:17 - | -LL | mod inner { #![reexport_test_harness_main="2900"] } - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ - -warning: crate-level attribute should be an inner attribute - --> $DIR/issue-43106-gating-of-builtin-attrs.rs:475:5 - | -LL | #[reexport_test_harness_main = "2900"] fn f() { } - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ - | -help: add a `!` - | -LL | #![reexport_test_harness_main = "2900"] fn f() { } - | + - -warning: crate-level attribute should be an inner attribute - --> $DIR/issue-43106-gating-of-builtin-attrs.rs:479:5 - | -LL | #[reexport_test_harness_main = "2900"] struct S; - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ - | -help: add a `!` - | -LL | #![reexport_test_harness_main = "2900"] struct S; - | + - -warning: crate-level attribute should be an inner attribute - --> $DIR/issue-43106-gating-of-builtin-attrs.rs:483:5 - | -LL | #[reexport_test_harness_main = "2900"] type T = S; - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ - | -help: add a `!` - | -LL | #![reexport_test_harness_main = "2900"] type T = S; - | + - -warning: crate-level attribute should be an inner attribute - --> $DIR/issue-43106-gating-of-builtin-attrs.rs:487:5 - | -LL | #[reexport_test_harness_main = "2900"] impl S { } - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ - | -help: add a `!` - | -LL | #![reexport_test_harness_main = "2900"] impl S { } - | + - warning: attribute should be applied to an `extern` block with non-Rust ABI --> $DIR/issue-43106-gating-of-builtin-attrs.rs:716:17 | @@ -771,6 +710,76 @@ LL | #[no_implicit_prelude] impl S { } = warning: this was previously accepted by the compiler but is being phased out; it will become a hard error in a future release! = help: `#[no_implicit_prelude]` can be applied to crates and modules +warning: crate-level attribute should be an inner attribute: add an exclamation mark: `#![reexport_test_harness_main]` + --> $DIR/issue-43106-gating-of-builtin-attrs.rs:468:1 + | +LL | #[reexport_test_harness_main = "2900"] + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + | +note: this attribute does not have an `!`, which means it is applied to this module + --> $DIR/issue-43106-gating-of-builtin-attrs.rs:470:1 + | +LL | / mod reexport_test_harness_main { +LL | | +LL | | mod inner { #![reexport_test_harness_main="2900"] } +... | +LL | | } + | |_^ + +warning: the `#![reexport_test_harness_main]` attribute can only be used at the crate root + --> $DIR/issue-43106-gating-of-builtin-attrs.rs:472:17 + | +LL | mod inner { #![reexport_test_harness_main="2900"] } + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +warning: crate-level attribute should be an inner attribute: add an exclamation mark: `#![reexport_test_harness_main]` + --> $DIR/issue-43106-gating-of-builtin-attrs.rs:475:5 + | +LL | #[reexport_test_harness_main = "2900"] fn f() { } + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + | +note: this attribute does not have an `!`, which means it is applied to this function + --> $DIR/issue-43106-gating-of-builtin-attrs.rs:475:44 + | +LL | #[reexport_test_harness_main = "2900"] fn f() { } + | ^^^^^^^^^^ + +warning: crate-level attribute should be an inner attribute: add an exclamation mark: `#![reexport_test_harness_main]` + --> $DIR/issue-43106-gating-of-builtin-attrs.rs:479:5 + | +LL | #[reexport_test_harness_main = "2900"] struct S; + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + | +note: this attribute does not have an `!`, which means it is applied to this struct + --> $DIR/issue-43106-gating-of-builtin-attrs.rs:479:44 + | +LL | #[reexport_test_harness_main = "2900"] struct S; + | ^^^^^^^^^ + +warning: crate-level attribute should be an inner attribute: add an exclamation mark: `#![reexport_test_harness_main]` + --> $DIR/issue-43106-gating-of-builtin-attrs.rs:483:5 + | +LL | #[reexport_test_harness_main = "2900"] type T = S; + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + | +note: this attribute does not have an `!`, which means it is applied to this type alias + --> $DIR/issue-43106-gating-of-builtin-attrs.rs:483:44 + | +LL | #[reexport_test_harness_main = "2900"] type T = S; + | ^^^^^^^^^^^ + +warning: crate-level attribute should be an inner attribute: add an exclamation mark: `#![reexport_test_harness_main]` + --> $DIR/issue-43106-gating-of-builtin-attrs.rs:487:5 + | +LL | #[reexport_test_harness_main = "2900"] impl S { } + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + | +note: this attribute does not have an `!`, which means it is applied to this implementation block + --> $DIR/issue-43106-gating-of-builtin-attrs.rs:487:44 + | +LL | #[reexport_test_harness_main = "2900"] impl S { } + | ^^^^^^^^^^ + warning: `#[macro_escape]` attribute cannot be used on functions --> $DIR/issue-43106-gating-of-builtin-attrs.rs:500:5 | diff --git a/tests/ui/target-feature/gate.rs b/tests/ui/target-feature/gate.rs index fc3763820cbec..ea3bbbed273c8 100644 --- a/tests/ui/target-feature/gate.rs +++ b/tests/ui/target-feature/gate.rs @@ -20,6 +20,7 @@ // gate-test-sparc_target_feature // gate-test-x87_target_feature // gate-test-m68k_target_feature +// gate-test-avr_target_feature #[target_feature(enable = "x87")] //~^ ERROR: currently unstable diff --git a/tests/ui/target-feature/gate.stderr b/tests/ui/target-feature/gate.stderr index 67df09fd369e4..f0de5a958e860 100644 --- a/tests/ui/target-feature/gate.stderr +++ b/tests/ui/target-feature/gate.stderr @@ -1,5 +1,5 @@ error[E0658]: the target feature `x87` is currently unstable - --> $DIR/gate.rs:24:18 + --> $DIR/gate.rs:25:18 | LL | #[target_feature(enable = "x87")] | ^^^^^^^^^^^^^^