diff --git a/Cargo.lock b/Cargo.lock index 73c3f74ce348f..f8f3dfce90c4e 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1811,19 +1811,6 @@ dependencies = [ "zerovec", ] -[[package]] -name = "icu_list" -version = "2.3.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5a5c625125085fac4bf9ad111888a90c6ab9dc7bcaec392ca79cab417f46e3fb" -dependencies = [ - "icu_provider", - "regex-automata", - "serde", - "writeable", - "zerovec", -] - [[package]] name = "icu_locale_core" version = "2.3.0" @@ -1832,32 +1819,11 @@ checksum = "d56e28588da92eee5c3201a6eff33fabdd49b62269c8938d4ff050ce4d900deb" dependencies = [ "displaydoc", "litemap", - "serde", "tinystr", "writeable", "zerovec", ] -[[package]] -name = "icu_locale_fallback" -version = "2.3.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "251af8e57c9400e3eb58242fe5b8b1152b2a64fdf4cf632f923c38ccee6f2fa9" -dependencies = [ - "icu_locale_core", - "icu_locale_fallback_data", - "icu_provider", - "potential_utf", - "tinystr", - "zerovec", -] - -[[package]] -name = "icu_locale_fallback_data" -version = "2.3.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "decf2a22ec8fa68f1a0c1129a3f8583f8f8bc24e8b9ccbe98ead99f62a4dc3a8" - [[package]] name = "icu_normalizer" version = "2.2.0" @@ -1906,8 +1872,6 @@ checksum = "92a7ed671a6aad807a8651a2e1782a6598fda9ce5185dd8158549e95a91c6428" dependencies = [ "displaydoc", "icu_locale_core", - "serde", - "stable_deref_trait", "writeable", "yoke", "zerofrom", @@ -3106,8 +3070,6 @@ version = "0.1.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b73949432f5e2a09657003c25bca5e19a0e9c84f8058ca374f49e0ebe605af77" dependencies = [ - "serde_core", - "writeable", "zerovec", ] @@ -3713,6 +3675,7 @@ dependencies = [ "rustc_ast_pretty", "rustc_data_structures", "rustc_error_messages", + "rustc_lint_defs", "rustc_macros", "rustc_serialize", "rustc_span", @@ -3745,16 +3708,6 @@ dependencies = [ "thin-vec", ] -[[package]] -name = "rustc_baked_icu_data" -version = "0.0.0" -dependencies = [ - "icu_list", - "icu_locale_fallback", - "icu_provider", - "zerovec", -] - [[package]] name = "rustc_borrowck" version = "0.0.0" @@ -4028,10 +3981,6 @@ name = "rustc_error_messages" version = "0.0.0" dependencies = [ "fluent-bundle", - "icu_list", - "icu_locale_core", - "intl-memoizer", - "rustc_baked_icu_data", "rustc_data_structures", "rustc_macros", "rustc_serialize", @@ -7008,7 +6957,6 @@ dependencies = [ "displaydoc", "yoke", "zerofrom", - "zerovec", ] [[package]] diff --git a/compiler/rustc_abi/src/layout.rs b/compiler/rustc_abi/src/layout.rs index 720efd43dd248..cf03f434fbce4 100644 --- a/compiler/rustc_abi/src/layout.rs +++ b/compiler/rustc_abi/src/layout.rs @@ -4,6 +4,7 @@ use std::num::NonZero; use std::ops::Deref; use std::range::{RangeFrom, RangeToInclusive}; +pub use coroutine::PackCoroutineLayout; use rustc_hashes::Hash64; use rustc_index::Idx; use rustc_index::bit_set::BitMatrix; diff --git a/compiler/rustc_abi/src/layout/coroutine.rs b/compiler/rustc_abi/src/layout/coroutine.rs index bc301869f5ce9..d44c53c56cc3b 100644 --- a/compiler/rustc_abi/src/layout/coroutine.rs +++ b/compiler/rustc_abi/src/layout/coroutine.rs @@ -30,6 +30,26 @@ use crate::{ StructKind, TagEncoding, VariantLayout, Variants, WrappingRange, }; +/// This option controls how coroutine saved locals are packed +/// into the coroutine state data +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)] +#[cfg_attr( + feature = "nightly", + derive( + rustc_macros::Encodable_NoContext, + rustc_macros::Decodable_NoContext, + rustc_macros::StableHash, + ) +)] +pub enum PackCoroutineLayout { + /// The classic layout where captures are always promoted to coroutine state prefix + #[default] + Classic, + /// Captures are first saved into the `UNRESUMED` state and promoted + /// when they are used across more than one suspension + CapturesOnly, +} + /// Overlap eligibility and variant assignment for each CoroutineSavedLocal. #[derive(Clone, Debug, PartialEq)] enum SavedLocalEligibility { diff --git a/compiler/rustc_abi/src/lib.rs b/compiler/rustc_abi/src/lib.rs index 1f2fcfc389f2c..b6944a72c0f89 100644 --- a/compiler/rustc_abi/src/lib.rs +++ b/compiler/rustc_abi/src/lib.rs @@ -72,7 +72,10 @@ pub use canon_abi::{ArmCall, CanonAbi, InterruptKind, X86Call}; #[cfg(feature = "nightly")] pub use extern_abi::CVariadicStatus; pub use extern_abi::{ExternAbi, all_names}; -pub use layout::{FIRST_VARIANT, FieldIdx, LayoutCalculator, LayoutCalculatorError, VariantIdx}; +pub use layout::{ + FIRST_VARIANT, FieldIdx, LayoutCalculator, LayoutCalculatorError, PackCoroutineLayout, + VariantIdx, +}; #[cfg(feature = "nightly")] pub use layout::{Layout, TyAbiInterface, TyAndLayout}; pub use wrapping_range::WrappingRange; diff --git a/compiler/rustc_attr_ir/Cargo.toml b/compiler/rustc_attr_ir/Cargo.toml index a1afc13cbd1e7..349d241d584c4 100644 --- a/compiler/rustc_attr_ir/Cargo.toml +++ b/compiler/rustc_attr_ir/Cargo.toml @@ -10,6 +10,7 @@ rustc_ast = { path = "../rustc_ast" } rustc_ast_pretty = { path = "../rustc_ast_pretty" } rustc_data_structures = { path = "../rustc_data_structures" } rustc_error_messages = { path = "../rustc_error_messages" } +rustc_lint_defs = { path = "../rustc_lint_defs" } rustc_macros = { path = "../rustc_macros" } rustc_serialize = { path = "../rustc_serialize" } rustc_span = { path = "../rustc_span" } diff --git a/compiler/rustc_attr_ir/src/attr.rs b/compiler/rustc_attr_ir/src/attr.rs index 48fb6293ea565..3bb7c13b265ad 100644 --- a/compiler/rustc_attr_ir/src/attr.rs +++ b/compiler/rustc_attr_ir/src/attr.rs @@ -5,6 +5,7 @@ use rustc_ast::token::DocFragmentKind; use rustc_ast::{AttrStyle, DelimArgs, MetaItemLit, ast, join_path_idents}; use rustc_data_structures::stable_hash::{StableHash, StableHashCtxt, StableHasher}; use rustc_error_messages::{DiagArgValue, IntoDiagArg}; +use rustc_lint_defs::ToolOptions; use rustc_macros::{Decodable, Encodable, StableHash}; use rustc_span::{AttrId, DUMMY_SP, Ident, Span, Symbol}; @@ -112,7 +113,7 @@ pub enum Attribute { /// /// Tool attributes, with the exception of diagnostic attributes, are not converted into a /// parsed form. - Tool(Box), + Tool { item: Box, opts: ToolOptions }, /// A derive helper attribute. /// @@ -125,7 +126,7 @@ pub enum Attribute { impl Attribute { pub fn value_lit(&self) -> Option<&MetaItemLit> { match &self { - Attribute::Tool(n) | Attribute::DeriveHelper(n) => match n.as_ref() { + Attribute::Tool { item: n, .. } | Attribute::DeriveHelper(n) => match n.as_ref() { AttrItem { args: AttrArgs::Eq { eq_span: _, expr }, .. } => Some(expr), _ => None, }, @@ -135,7 +136,7 @@ impl Attribute { pub fn is_prefix_attr_for_suggestions(&self) -> bool { match self { - Attribute::Tool(attr) | Attribute::DeriveHelper(attr) => { + Attribute::Tool { item: attr, .. } | Attribute::DeriveHelper(attr) => { attr.span.desugaring_kind().is_none() } // Other parsed attributes that can appear on expressions originate from source and diff --git a/compiler/rustc_attr_ir/src/data_structures.rs b/compiler/rustc_attr_ir/src/data_structures.rs index 323a66f96ec3f..0f78810054963 100644 --- a/compiler/rustc_attr_ir/src/data_structures.rs +++ b/compiler/rustc_attr_ir/src/data_structures.rs @@ -12,6 +12,7 @@ use rustc_ast::token::DocFragmentKind; use rustc_ast::{AttrStyle, Path, ast}; use rustc_data_structures::fx::FxIndexMap; use rustc_error_messages::{DiagArgValue, IntoDiagArg}; +use rustc_lint_defs::ToolOptions; use rustc_macros::{ Decodable, Decodable_NoContext, Encodable, Encodable_NoContext, PrintAttribute, StableHash, }; @@ -1167,8 +1168,8 @@ pub enum AttributeKind { /// Represents `#[register_attribute_tool]`, `#[register_lint_tool]` and `#[register_tool]` RegisterTool { - attr_tools: ThinVec, - lint_tools: ThinVec, + attr_tools: ThinVec<(Ident, ToolOptions)>, + lint_tools: ThinVec<(Ident, ToolOptions)>, }, /// Represents [`#[repr]`](https://doc.rust-lang.org/stable/reference/type-layout.html#representations). diff --git a/compiler/rustc_attr_ir/src/lib.rs b/compiler/rustc_attr_ir/src/lib.rs index 99ad8f522aaf3..5e02d953b67a3 100644 --- a/compiler/rustc_attr_ir/src/lib.rs +++ b/compiler/rustc_attr_ir/src/lib.rs @@ -132,7 +132,7 @@ macro_rules! find_attr { $crate::Attribute::Parsed($pattern) $(if $guard)? => { break 'done Some($e); } - $crate::Attribute::Tool(..) | $crate::Attribute::DeriveHelper(..) => {} + $crate::Attribute::Tool {..} | $crate::Attribute::DeriveHelper(..) => {} // In lint emitting, there's a specific exception for this warning. // It's not usually emitted from inside macros from other crates // (see https://github.com/rust-lang/rust/issues/110613) diff --git a/compiler/rustc_attr_ir/src/pretty_printing.rs b/compiler/rustc_attr_ir/src/pretty_printing.rs index 4ffd0f07029a3..04e5b94921860 100644 --- a/compiler/rustc_attr_ir/src/pretty_printing.rs +++ b/compiler/rustc_attr_ir/src/pretty_printing.rs @@ -11,6 +11,7 @@ use rustc_ast::token::{CommentKind, DocFragmentKind}; use rustc_ast::{AttrId, AttrStyle, IntTy, UintTy}; use rustc_ast_pretty::pp::Printer; use rustc_data_structures::fx::FxIndexMap; +use rustc_lint_defs::{Reflectiveness, ToolOptions}; use rustc_span::def_id::DefId; use rustc_span::hygiene::Transparency; use rustc_span::{ErrorGuaranteed, Ident, Span, Symbol}; @@ -226,4 +227,6 @@ print_debug!( NativeLibKind, CollapseMacroDebuginfo, LintName, + ToolOptions, + Reflectiveness, ); diff --git a/compiler/rustc_attr_parsing/src/attributes/codegen_attrs.rs b/compiler/rustc_attr_parsing/src/attributes/codegen_attrs.rs index e88b1751e4b6c..7da22862f7e80 100644 --- a/compiler/rustc_attr_parsing/src/attributes/codegen_attrs.rs +++ b/compiler/rustc_attr_parsing/src/attributes/codegen_attrs.rs @@ -294,7 +294,7 @@ impl AttributeParser for NakedParser { if other_attr .segments() .next() - .is_some_and(|i| tools.iter().any(|tool| tool.name == i.name)) + .is_some_and(|i| tools.iter().any(|(tool, _)| tool.name == i.name)) { // effectively skips the error message being emitted below // if it's a tool attribute diff --git a/compiler/rustc_attr_parsing/src/attributes/crate_level.rs b/compiler/rustc_attr_parsing/src/attributes/crate_level.rs index 4f86895bbd02b..f601025b68b10 100644 --- a/compiler/rustc_attr_parsing/src/attributes/crate_level.rs +++ b/compiler/rustc_attr_parsing/src/attributes/crate_level.rs @@ -1,14 +1,18 @@ use rustc_attr_ir::WindowsSubsystemKind; -use rustc_data_structures::fx::FxIndexSet; +use rustc_data_structures::fx::FxIndexMap; use rustc_feature::AttributeStability; +use rustc_lint_defs::Reflectiveness::{NonReflective, Reflective}; +use rustc_lint_defs::ToolOptions; use rustc_lint_defs::builtin::{DUPLICATE_TOOLS, UNKNOWN_CRATE_TYPES}; +use rustc_session::diagnostics::feature_err; use rustc_span::Symbol; use rustc_span::edit_distance::find_best_match_for_name_with_substrings; use rustc_structures::CrateType; use super::prelude::*; use crate::diagnostics::{ - DuplicateTool, ToolReserved, UnknownCrateTypes, UnknownCrateTypesSuggestion, + DuplicateTool, PredefinedToolReflective, ToolReserved, UnknownCrateTypes, + UnknownCrateTypesSuggestion, UnrecognizedToolOption, }; pub(crate) struct CrateNameParser; @@ -323,12 +327,15 @@ impl CombineAttributeParser for FeatureParser { #[derive(Default)] pub(crate) struct RegisterToolParser { - attr_tools: FxIndexSet, - lint_tools: FxIndexSet, + attr_tools: FxIndexMap, + lint_tools: FxIndexMap, } +pub const PREDEFINED_TOOLS: &[Symbol] = + &[sym::clippy, sym::rustfmt, sym::diagnostic, sym::miri, sym::rust_analyzer]; + fn parse_register_tool( - tools: &mut [&mut FxIndexSet], + tools: &mut [&mut FxIndexMap], cx: &mut AcceptContext<'_, '_>, args: &ArgParser, ) { @@ -346,9 +353,6 @@ fn parse_register_tool( cx.adcx().expected_identifier(elem.span()); continue; }; - let Some(()) = cx.expect_no_args(elem.args()) else { - continue; - }; let path = elem.path(); let Some(ident) = path.word() else { @@ -366,9 +370,60 @@ fn parse_register_tool( continue; } + let reflectiveness = + match elem.args() { + ArgParser::NoArgs => NonReflective, + ArgParser::List(list) => 'reflect: { + // features are not available during first pass, gate is emitted during second pass + if cx.features.is_some_and(|f| !f.type_info()) { + feature_err( + cx.sess(), + sym::type_info, + elem.span(), + "tool attribute options are currently unstable", + ) + .emit(); + break 'reflect NonReflective; + } + + let Some(itm) = cx.expect_single(list) else { + break 'reflect NonReflective; + }; + + let Some(itm) = itm.meta_item_no_args() else { + cx.adcx().expected_no_args(itm.span()); + break 'reflect NonReflective; + }; + + if !itm.path().word_is(sym::reflect) { + cx.should_emit.emit_err(cx.dcx().create_err(UnrecognizedToolOption { + span: itm.span(), + option: itm.path().get_attribute_path(), + })); + + break 'reflect NonReflective; + } + + if PREDEFINED_TOOLS.iter().any(|t| t == &ident.name) { + cx.should_emit.emit_err(cx.dcx().create_err(PredefinedToolReflective { + span: elem.span(), + tool: ident, + })); + + break 'reflect NonReflective; + } + + Reflective + } + ArgParser::NameValue(_) => { + cx.adcx().expected_list_or_no_args(elem.span()); + NonReflective + } + }; + let mut lint_emitted = false; for tools in tools.iter_mut() { - if let Some(old_ident) = tools.replace(ident) + let opts = if let Some((old_ident, old_opts)) = tools.get_key_value(&ident) && !lint_emitted { lint_emitted = true; @@ -377,7 +432,13 @@ fn parse_register_tool( DuplicateTool { span: ident.span, tool: ident, old_ident_span: old_ident.span }, ident.span, ); - } + + old_opts.union(ToolOptions { reflectiveness }) + } else { + ToolOptions { reflectiveness } + }; + + tools.insert(ident, opts); } } } @@ -386,7 +447,7 @@ impl AttributeParser for RegisterToolParser { const ATTRIBUTES: AcceptMapping = &[ ( &[sym::register_tool], - template!(List: &["tool1, tool2, ..."]), + template!(List: &["tool1, tool2(reflect), ..."]), unstable!(register_tool), |this, cx, args| { parse_register_tool(&mut [&mut this.attr_tools, &mut this.lint_tools], cx, args) @@ -394,13 +455,13 @@ impl AttributeParser for RegisterToolParser { ), ( &[sym::register_attribute_tool], - template!(List: &["tool1, tool2, ..."]), + template!(List: &["tool1, tool2(reflect), ..."]), unstable!(register_tool), |this, cx, args| parse_register_tool(&mut [&mut this.attr_tools], cx, args), ), ( &[sym::register_lint_tool], - template!(List: &["tool1, tool2, ..."]), + template!(List: &["tool1, tool2(reflect), ..."]), unstable!(register_tool), |this, cx, args| parse_register_tool(&mut [&mut this.lint_tools], cx, args), ), diff --git a/compiler/rustc_attr_parsing/src/diagnostics.rs b/compiler/rustc_attr_parsing/src/diagnostics.rs index 868f4b347a27f..39bd300957f5c 100644 --- a/compiler/rustc_attr_parsing/src/diagnostics.rs +++ b/compiler/rustc_attr_parsing/src/diagnostics.rs @@ -948,6 +948,24 @@ pub(crate) struct ToolReserved { pub(crate) tool: Ident, } +#[derive(Diagnostic)] +#[diag("unrecognized tool option `{$option}`")] +pub(crate) struct UnrecognizedToolOption { + #[primary_span] + pub(crate) span: Span, + pub(crate) option: AttrPath, +} + +#[derive(Diagnostic)] +#[diag( + "the tool attribute `{$tool}` is predefined and cannot be marked as being available for reflection" +)] +pub(crate) struct PredefinedToolReflective { + #[primary_span] + pub(crate) span: Span, + pub(crate) tool: Ident, +} + #[derive(Diagnostic)] #[diag("unknown diagnostic attribute")] pub(crate) struct UnknownDiagnosticAttribute { diff --git a/compiler/rustc_attr_parsing/src/interface.rs b/compiler/rustc_attr_parsing/src/interface.rs index 92cf6813bd22e..8510b54aa6446 100644 --- a/compiler/rustc_attr_parsing/src/interface.rs +++ b/compiler/rustc_attr_parsing/src/interface.rs @@ -10,9 +10,10 @@ use rustc_attr_ir::{AttrArgs, AttrItem, AttrPath, Attribute, AttributeKind, Hash use rustc_data_structures::sync::{DynSend, DynSync}; use rustc_errors::{Diag, DiagCtxtHandle, Diagnostic, Level, MultiSpan}; use rustc_feature::{BUILTIN_ATTRIBUTE_SET, Features}; -use rustc_lint_defs::{LintId, RegisteredTools}; +use rustc_lint_defs::Reflectiveness::NonReflective; +use rustc_lint_defs::{LintId, RegisteredTools, ToolOptions}; use rustc_session::Session; -use rustc_span::{DUMMY_SP, ErrorGuaranteed, Span, Symbol, sym}; +use rustc_span::{DUMMY_SP, ErrorGuaranteed, Ident, Span, Symbol, sym}; use crate::attributes::AttributeSafety; use crate::attributes::doc_comment::target_check_doc_comment; @@ -470,7 +471,7 @@ impl<'sess> AttributeParser<'sess> { // we could be here in the `#[lint::attribute_macro] not found` case, // which recovers with a `NonMacroAttr` res. if let Some(tools) = self.attr_tools - && tools.iter().any(|i| i.name == sym::lint) + && tools.iter().any(|(i, _)| i.name == sym::lint) { self.emit_err(diagnostics::UnknownLintHelper { span: n.item.span, @@ -507,7 +508,19 @@ impl<'sess> AttributeParser<'sess> { let attr = match attr_path.segments.len() { 0 => unreachable!("no path for {attr:?}"), 1 => Attribute::DeriveHelper(Box::new(attr)), - _ => Attribute::Tool(Box::new(attr)), + _ => { + if let Some(tools) = self.attr_tools + && let Some(opts) = + tools.get(&Ident::with_dummy_span(attr_path.segments[0])) + { + Attribute::Tool { item: Box::new(attr), opts: opts.clone() } + } else { + Attribute::Tool { + item: Box::new(attr), + opts: ToolOptions { reflectiveness: NonReflective }, + } + } + } }; attributes.push(attr); diff --git a/compiler/rustc_attr_parsing/src/lib.rs b/compiler/rustc_attr_parsing/src/lib.rs index e749fce53bd14..a348bcdc3fc47 100644 --- a/compiler/rustc_attr_parsing/src/lib.rs +++ b/compiler/rustc_attr_parsing/src/lib.rs @@ -116,6 +116,7 @@ pub use attributes::cfg::{ CFG_TEMPLATE, EvalConfigResult, eval_config_entry, parse_cfg, parse_cfg_attr, parse_cfg_entry, }; pub use attributes::cfg_select::*; +pub use attributes::crate_level::PREDEFINED_TOOLS; pub use attributes::util::{is_builtin_attr, parse_version}; pub use context::ShouldEmit; pub use diagnostics::{ParsedDescription, UnusedMultiple}; diff --git a/compiler/rustc_attr_parsing/src/target_checking.rs b/compiler/rustc_attr_parsing/src/target_checking.rs index 887b269881cee..ede3e24dd0ccf 100644 --- a/compiler/rustc_attr_parsing/src/target_checking.rs +++ b/compiler/rustc_attr_parsing/src/target_checking.rs @@ -380,7 +380,9 @@ impl<'sess> AttributeParser<'sess> { Attribute::Parsed(AttributeKind::Doc(attr)) => Some(attr.first_span), // Checked during attribute parsing target checking Attribute::Parsed(_) => None, - Attribute::Tool(attr) | Attribute::DeriveHelper(attr) => Some(attr.span), + Attribute::Tool { item: attr, .. } | Attribute::DeriveHelper(attr) => { + Some(attr.span) + } } }) .collect::>(); diff --git a/compiler/rustc_baked_icu_data/Cargo.toml b/compiler/rustc_baked_icu_data/Cargo.toml deleted file mode 100644 index 072084e8ff061..0000000000000 --- a/compiler/rustc_baked_icu_data/Cargo.toml +++ /dev/null @@ -1,12 +0,0 @@ -[package] -name = "rustc_baked_icu_data" -version = "0.0.0" -edition = "2024" - -[dependencies] -# tidy-alphabetical-start -icu_list = { version = "2.3", default-features = false } -icu_locale_fallback = { version = "2.3", default-features = false, features = ["compiled_data"] } -icu_provider = { version = "2.3", features = ["baked", "sync"] } -zerovec = "0.11.0" -# tidy-alphabetical-end diff --git a/compiler/rustc_baked_icu_data/src/data/list_and_v1.rs.data b/compiler/rustc_baked_icu_data/src/data/list_and_v1.rs.data deleted file mode 100644 index 6a0d2bf61e49e..0000000000000 --- a/compiler/rustc_baked_icu_data/src/data/list_and_v1.rs.data +++ /dev/null @@ -1,71 +0,0 @@ -// @generated -/// Implement `DataProvider` on the given struct using the data -/// hardcoded in this file. This allows the struct to be used with -/// `icu`'s `_unstable` constructors. -/// -/// Using this implementation will embed the following data in the binary's data segment: -/// * 179B for the lookup data structure (33 data identifiers) -/// * 4183B[^1] for the actual data (11 unique structs) -/// -/// [^1]: these numbers can be smaller in practice due to linker deduplication -/// -/// This macro requires the following crates: -/// * `icu_list` -/// * `icu_locale_fallback/compiled_data` -/// * `icu_provider` -/// * `icu_provider/baked` -/// * `zerovec` -#[doc(hidden)] -#[macro_export] -macro_rules! __impl_list_and_v1 { - ($ provider : ty) => { - #[clippy::msrv = "1.88"] - const _: () = <$provider>::MUST_USE_MAKE_PROVIDER_MACRO; - #[clippy::msrv = "1.88"] - impl $provider { - const DATA_LIST_AND_V1: icu_provider::baked::zerotrie::Data = { - const TRIE: icu_provider::baked::zerotrie::ZeroTrieSimpleAscii<&'static [u8]> = icu_provider::baked::zerotrie::ZeroTrieSimpleAscii { store: b"\xC8efijprtz\x18#.9DOZ\xC2ns\n\x1E\xC3NSW\x01\x02\x80\x85\x8A\x1E\xC3NSW\x01\x02\x81\x81\x81r\x1E\xC3NSW\x01\x02\x80\x86\x86t\x1E\xC3NSW\x01\x02\x82\x82\x82a\x1E\xC3NSW\x01\x02\x83\x83\x83t\x1E\xC3NSW\x01\x02\x80\x82\x82u\x1E\xC3NSW\x01\x02\x80\x87\x87r\x1E\xC3NSW\x01\x02\x80\x88\x88h\xC2\x1E-\t\xC3NSW\x01\x02\x83\x89\x89Han\xC2st\n\x1E\xC3NSW\x01\x02\x83\x89\x89\x1E\xC3NSW\x01\x02\x84\x89\x89" }; - const VALUES: &'static [::DataStruct] = &[icu_list::provider::ListFormatterPatterns { start: icu_list::provider::ListJoinerPattern::from_parts(unsafe { zerovec::VarZeroCow::from_bytes_unchecked(b", ") }, 2u8), middle: unsafe { zerovec::VarZeroCow::from_bytes_unchecked(b", ") }, end: icu_list::provider::ConditionalListJoinerPattern { default: icu_list::provider::ListJoinerPattern::from_parts(unsafe { zerovec::VarZeroCow::from_bytes_unchecked(b", ") }, 2u8), special_case: None }, pair: None }, icu_list::provider::ListFormatterPatterns { start: icu_list::provider::ListJoinerPattern::from_parts(unsafe { zerovec::VarZeroCow::from_bytes_unchecked(b", ") }, 2u8), middle: unsafe { zerovec::VarZeroCow::from_bytes_unchecked(b", ") }, end: icu_list::provider::ConditionalListJoinerPattern { default: icu_list::provider::ListJoinerPattern::from_parts(unsafe { zerovec::VarZeroCow::from_bytes_unchecked(b" y ") }, 3u8), special_case: Some(icu_list::provider::SpecialCasePattern { condition: unsafe { icu_list::provider::SerdeDFA::from_dfa_bytes_unchecked(if cfg!(target_endian = "little") { b"rust-regex-automata-dfa-sparse\0\0\xFF\xFE\0\0\x02\0\0\0\0\0\0\0\x02\0\0\0\x0E\0\0\0\x01\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\x01\x02\x02\x02\x03\x04\x04\x05\x06\x07\x07\x07\x07\x07\x07\x07\x07\x07\x07\x07\x07\x07\x07\x07\x07\x07\x07\x07\x07\x07\x07\x07\x08\t\t\t\n\x0B\x0B\x0C\r\x0E\x0E\x0E\x0E\x0E\x0E\x0E\x0E\x0E\x0E\x0E\x0E\x0E\x0E\x0E\x0E\x0E\x0E\x0E\x0E\x0E\x0E\x0F\x0F\x0F\x0F\x0F\x0F\x0F\x0F\x0F\x0F\x0F\x0F\x0F\x0F\x0F\x0F\x10\x10\x10\x10\x10\x10\x10\x10\x10\x10\x10\x10\x10\x10\x10\x10\x11\x11\x11\x11\x11\x11\x11\x11\x11\x11\x11\x11\x11\x11\x11\x11\x11\x11\x11\x11\x11\x11\x11\x11\x11\x11\x11\x11\x11\x11\x11\x11\x12\x12\x13\x13\x13\x13\x13\x13\x13\x13\x13\x13\x13\x13\x13\x13\x13\x13\x13\x13\x13\x13\x13\x13\x13\x13\x13\x13\x13\x13\x13\x13\x14\x15\x15\x15\x15\x15\x15\x15\x15\x15\x15\x15\x15\x16\x17\x17\x18\x19\x19\x19\x1A\x1B\x1B\x1B\x1B\x1B\x1B\x1B\x1B\x1B\x1B\x1B(\x01\0\0\x01\0\0\0\0\0\0\0\0\x01\0\0\0\0\0\0\0\0\x01\x80\0\0\0\0\0\0\x01\0\0\0\0\0\0\0\0\x05\0\x05\x05\x06\x06\x0C\x0C\r\r\0\0S\0\0\0D\0\0\0S\0\0\0D\0\0\0\0\0\0\0\0\x02\0\0\x1B\0\0\x12\0\0\0\x12\0\0\0\0\x03\0\x06\x06\r\r\0\0h\0\0\0h\0\0\0\0\0\0\0\0\x0E\0\0\0\x02\x02\x04\x07\t\t\x0B\x0E\x13\x13\x14\x14\x15\x15\x16\x16\x17\x17\x18\x18\x19\x19\x1A\x1A\0\0D\0\0\0D\0\0\0D\0\0\0D\0\0\0D\0\0\0\xBF\0\0\0\xCE\0\0\0\xDD\0\0\0\xEC\0\0\0\xDD\0\0\0\xFB\0\0\0\n\x01\0\0\x19\x01\0\0\x12\0\0\0\0\x02\0\x0F\x11\0\0D\0\0\0\0\0\0\0\0\x02\0\x11\x11\0\0\xBF\0\0\0\0\0\0\0\0\x02\0\x0F\x11\0\0\xBF\0\0\0\0\0\0\0\0\x02\0\x0F\x10\0\0\xBF\0\0\0\0\0\0\0\0\x02\0\x10\x11\0\0\xDD\0\0\0\0\0\0\0\0\x02\0\x0F\x11\0\0\xDD\0\0\0\0\0\0\0\0\x02\0\x0F\x0F\0\0\xDD\0\0\0\0\0\0\0\0\x02\0\0\0\0\0\0\0\0\0\0\0\0\0\x03\0\0\x04\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\0\0\0\0\0\0\0\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\0\0\0\0\x01\0\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\x06\0\0\0\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF#\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0#\0\0\0#\0\0\0#\0\0\0#\0\0\0#\0\0\0#\0\0\0\x12\0\0\0\t\0\0\0\x12\0\0\0\x12\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0" } else { b"rust-regex-automata-dfa-sparse\0\0\0\0\xFE\xFF\0\0\0\x02\0\0\0\0\0\0\0\x02\0\0\0\x0E\0\0\0\x01\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\x01\x02\x02\x02\x03\x04\x04\x05\x06\x07\x07\x07\x07\x07\x07\x07\x07\x07\x07\x07\x07\x07\x07\x07\x07\x07\x07\x07\x07\x07\x07\x07\x08\t\t\t\n\x0B\x0B\x0C\r\x0E\x0E\x0E\x0E\x0E\x0E\x0E\x0E\x0E\x0E\x0E\x0E\x0E\x0E\x0E\x0E\x0E\x0E\x0E\x0E\x0E\x0E\x0F\x0F\x0F\x0F\x0F\x0F\x0F\x0F\x0F\x0F\x0F\x0F\x0F\x0F\x0F\x0F\x10\x10\x10\x10\x10\x10\x10\x10\x10\x10\x10\x10\x10\x10\x10\x10\x11\x11\x11\x11\x11\x11\x11\x11\x11\x11\x11\x11\x11\x11\x11\x11\x11\x11\x11\x11\x11\x11\x11\x11\x11\x11\x11\x11\x11\x11\x11\x11\x12\x12\x13\x13\x13\x13\x13\x13\x13\x13\x13\x13\x13\x13\x13\x13\x13\x13\x13\x13\x13\x13\x13\x13\x13\x13\x13\x13\x13\x13\x13\x13\x14\x15\x15\x15\x15\x15\x15\x15\x15\x15\x15\x15\x15\x16\x17\x17\x18\x19\x19\x19\x1A\x1B\x1B\x1B\x1B\x1B\x1B\x1B\x1B\x1B\x1B\x1B\0\0\x01(\0\x01\0\0\0\0\0\0\0\0\x01\0\0\0\0\0\0\0\x80\x01\0\0\0\0\0\0\0\0\0\x01\0\0\0\0\0\0\x05\x05\x05\x06\x06\x0C\x0C\r\r\0\0\0\0\0S\0\0\0D\0\0\0S\0\0\0D\0\0\0\0\0\0\x02\0\x1B\0\0\0\0\0\x12\0\0\0\x12\0\0\x03\x06\x06\r\r\0\0\0\0\0h\0\0\0h\0\0\0\0\0\0\x0E\0\0\x02\x02\x04\x07\t\t\x0B\x0E\x13\x13\x14\x14\x15\x15\x16\x16\x17\x17\x18\x18\x19\x19\x1A\x1A\0\0\0\0\0D\0\0\0D\0\0\0D\0\0\0D\0\0\0D\0\0\0\xBF\0\0\0\xCE\0\0\0\xDD\0\0\0\xEC\0\0\0\xDD\0\0\0\xFB\0\0\x01\n\0\0\x01\x19\0\0\0\x12\0\0\x02\x0F\x11\0\0\0\0\0D\0\0\0\0\0\0\x02\x11\x11\0\0\0\0\0\xBF\0\0\0\0\0\0\x02\x0F\x11\0\0\0\0\0\xBF\0\0\0\0\0\0\x02\x0F\x10\0\0\0\0\0\xBF\0\0\0\0\0\0\x02\x10\x11\0\0\0\0\0\xDD\0\0\0\0\0\0\x02\x0F\x11\0\0\0\0\0\xDD\0\0\0\0\0\0\x02\x0F\x0F\0\0\0\0\0\xDD\0\0\0\0\0\0\0\0\x02\0\0\0\0\0\0\0\0\0\0\x03\0\0\x04\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\0\0\0\0\0\0\0\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\0\0\0\0\x01\0\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\x06\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\0\0\0#\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0#\0\0\0#\0\0\0#\0\0\0#\0\0\0#\0\0\0#\0\0\0\x12\0\0\0\t\0\0\0\x12\0\0\0\x12\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0" }) }, pattern: icu_list::provider::ListJoinerPattern::from_parts(unsafe { zerovec::VarZeroCow::from_bytes_unchecked(b" e ") }, 3u8) }) }, pair: None }, icu_list::provider::ListFormatterPatterns { start: icu_list::provider::ListJoinerPattern::from_parts(unsafe { zerovec::VarZeroCow::from_bytes_unchecked(b", ") }, 2u8), middle: unsafe { zerovec::VarZeroCow::from_bytes_unchecked(b", ") }, end: icu_list::provider::ConditionalListJoinerPattern { default: icu_list::provider::ListJoinerPattern::from_parts(unsafe { zerovec::VarZeroCow::from_bytes_unchecked(b" e ") }, 3u8), special_case: None }, pair: None }, icu_list::provider::ListFormatterPatterns { start: icu_list::provider::ListJoinerPattern::from_parts(unsafe { zerovec::VarZeroCow::from_bytes_unchecked(b"\xE3\x80\x81") }, 3u8), middle: unsafe { zerovec::VarZeroCow::from_bytes_unchecked(b"\xE3\x80\x81") }, end: icu_list::provider::ConditionalListJoinerPattern { default: icu_list::provider::ListJoinerPattern::from_parts(unsafe { zerovec::VarZeroCow::from_bytes_unchecked(b"\xE3\x80\x81") }, 3u8), special_case: None }, pair: None }, icu_list::provider::ListFormatterPatterns { start: icu_list::provider::ListJoinerPattern::from_parts(unsafe { zerovec::VarZeroCow::from_bytes_unchecked(b"\xE3\x80\x81") }, 3u8), middle: unsafe { zerovec::VarZeroCow::from_bytes_unchecked(b"\xE3\x80\x81") }, end: icu_list::provider::ConditionalListJoinerPattern { default: icu_list::provider::ListJoinerPattern::from_parts(unsafe { zerovec::VarZeroCow::from_bytes_unchecked(b"\xE5\x92\x8C") }, 3u8), special_case: None }, pair: Some(icu_list::provider::ConditionalListJoinerPattern { default: icu_list::provider::ListJoinerPattern::from_parts(unsafe { zerovec::VarZeroCow::from_bytes_unchecked(b"\xE3\x80\x81") }, 3u8), special_case: None }) }, icu_list::provider::ListFormatterPatterns { start: icu_list::provider::ListJoinerPattern::from_parts(unsafe { zerovec::VarZeroCow::from_bytes_unchecked(b", ") }, 2u8), middle: unsafe { zerovec::VarZeroCow::from_bytes_unchecked(b", ") }, end: icu_list::provider::ConditionalListJoinerPattern { default: icu_list::provider::ListJoinerPattern::from_parts(unsafe { zerovec::VarZeroCow::from_bytes_unchecked(b", & ") }, 4u8), special_case: None }, pair: Some(icu_list::provider::ConditionalListJoinerPattern { default: icu_list::provider::ListJoinerPattern::from_parts(unsafe { zerovec::VarZeroCow::from_bytes_unchecked(b" & ") }, 3u8), special_case: None }) }, icu_list::provider::ListFormatterPatterns { start: icu_list::provider::ListJoinerPattern::from_parts(unsafe { zerovec::VarZeroCow::from_bytes_unchecked(b", ") }, 2u8), middle: unsafe { zerovec::VarZeroCow::from_bytes_unchecked(b", ") }, end: icu_list::provider::ConditionalListJoinerPattern { default: icu_list::provider::ListJoinerPattern::from_parts(unsafe { zerovec::VarZeroCow::from_bytes_unchecked(b" et ") }, 4u8), special_case: None }, pair: None }, icu_list::provider::ListFormatterPatterns { start: icu_list::provider::ListJoinerPattern::from_parts(unsafe { zerovec::VarZeroCow::from_bytes_unchecked(b", ") }, 2u8), middle: unsafe { zerovec::VarZeroCow::from_bytes_unchecked(b", ") }, end: icu_list::provider::ConditionalListJoinerPattern { default: icu_list::provider::ListJoinerPattern::from_parts(unsafe { zerovec::VarZeroCow::from_bytes_unchecked(b" \xD0\xB8 ") }, 4u8), special_case: None }, pair: None }, icu_list::provider::ListFormatterPatterns { start: icu_list::provider::ListJoinerPattern::from_parts(unsafe { zerovec::VarZeroCow::from_bytes_unchecked(b", ") }, 2u8), middle: unsafe { zerovec::VarZeroCow::from_bytes_unchecked(b", ") }, end: icu_list::provider::ConditionalListJoinerPattern { default: icu_list::provider::ListJoinerPattern::from_parts(unsafe { zerovec::VarZeroCow::from_bytes_unchecked(b" ve ") }, 4u8), special_case: None }, pair: None }, icu_list::provider::ListFormatterPatterns { start: icu_list::provider::ListJoinerPattern::from_parts(unsafe { zerovec::VarZeroCow::from_bytes_unchecked(b"\xE3\x80\x81") }, 3u8), middle: unsafe { zerovec::VarZeroCow::from_bytes_unchecked(b"\xE3\x80\x81") }, end: icu_list::provider::ConditionalListJoinerPattern { default: icu_list::provider::ListJoinerPattern::from_parts(unsafe { zerovec::VarZeroCow::from_bytes_unchecked(b"\xE5\x92\x8C") }, 3u8), special_case: None }, pair: None }, icu_list::provider::ListFormatterPatterns { start: icu_list::provider::ListJoinerPattern::from_parts(unsafe { zerovec::VarZeroCow::from_bytes_unchecked(b", ") }, 2u8), middle: unsafe { zerovec::VarZeroCow::from_bytes_unchecked(b", ") }, end: icu_list::provider::ConditionalListJoinerPattern { default: icu_list::provider::ListJoinerPattern::from_parts(unsafe { zerovec::VarZeroCow::from_bytes_unchecked(b", and ") }, 6u8), special_case: None }, pair: Some(icu_list::provider::ConditionalListJoinerPattern { default: icu_list::provider::ListJoinerPattern::from_parts(unsafe { zerovec::VarZeroCow::from_bytes_unchecked(b" and ") }, 5u8), special_case: None }) }]; - unsafe { icu_provider::baked::zerotrie::Data::from_trie_and_values_unchecked(TRIE, VALUES) } - }; - } - #[clippy::msrv = "1.88"] - impl icu_provider::DataProvider for $provider { - fn load(&self, req: icu_provider::DataRequest) -> Result, icu_provider::DataError> { - let mut metadata = icu_provider::DataResponseMetadata::default(); - let payload = if let Some(payload) = icu_provider::baked::DataStore::get(&Self::DATA_LIST_AND_V1, req.id, req.metadata.attributes_prefix_match) { - payload - } else { - const FALLBACKER: icu_locale_fallback::LocaleFallbackerWithConfig<'static> = icu_locale_fallback::LocaleFallbacker::new().for_config(::INFO.fallback_config); - let mut fallback_iterator = FALLBACKER.fallback_for(req.id.locale.clone()); - loop { - if let Some(payload) = icu_provider::baked::DataStore::get(&Self::DATA_LIST_AND_V1, icu_provider::DataIdentifierBorrowed::for_marker_attributes_and_locale(req.id.marker_attributes, fallback_iterator.get()), req.metadata.attributes_prefix_match) { - metadata.locale = Some(fallback_iterator.take()); - break payload; - } - if fallback_iterator.get().is_unknown() { - return Err(icu_provider::DataErrorKind::IdentifierNotFound.with_req(::INFO, req)); - } - fallback_iterator.step(); - } - }; - Ok(icu_provider::DataResponse { payload, metadata }) - } - } - }; - ($ provider : ty , ITER) => { - __impl_list_and_v1!($provider); - #[clippy::msrv = "1.88"] - impl icu_provider::IterableDataProvider for $provider { - fn iter_ids(&self) -> Result>, icu_provider::DataError> { - Ok(icu_provider::baked::DataStore::iter(&Self::DATA_LIST_AND_V1).collect()) - } - } - }; - ($ provider : ty , DRY) => {}; - ($ provider : ty , DRY , ITER) => { - __impl_list_and_v1!($provider, ITER); - }; -} -#[doc(inline)] -pub use __impl_list_and_v1 as impl_list_and_v1; diff --git a/compiler/rustc_baked_icu_data/src/data/mod.rs b/compiler/rustc_baked_icu_data/src/data/mod.rs deleted file mode 100644 index 61d39d153db68..0000000000000 --- a/compiler/rustc_baked_icu_data/src/data/mod.rs +++ /dev/null @@ -1,40 +0,0 @@ -// @generated -include!("list_and_v1.rs.data"); -/// Marks a type as a data provider. You can then use macros like -/// `impl_core_helloworld_v1` to add implementations. -/// -/// ```ignore -/// struct MyProvider; -/// const _: () = { -/// include!("path/to/generated/macros.rs"); -/// make_provider!(MyProvider); -/// impl_core_helloworld_v1!(MyProvider); -/// } -/// ``` -#[doc(hidden)] -#[macro_export] -macro_rules! __make_provider { - ($ name : ty) => { - #[clippy::msrv = "1.88"] - impl $name { - #[allow(dead_code)] - pub(crate) const MUST_USE_MAKE_PROVIDER_MACRO: () = (); - } - icu_provider::marker::impl_data_provider_never_marker!($name); - }; -} -#[doc(inline)] -pub use __make_provider as make_provider; -/// This macro requires the following crates: -/// * `icu_list` -/// * `icu_locale_fallback/compiled_data` -/// * `icu_provider` -/// * `icu_provider/baked` -/// * `zerovec` -#[allow(unused_macros)] -macro_rules! impl_data_provider { - ($ provider : ty) => { - make_provider!($provider); - impl_list_and_v1!($provider); - }; -} diff --git a/compiler/rustc_baked_icu_data/src/lib.rs b/compiler/rustc_baked_icu_data/src/lib.rs deleted file mode 100644 index 1116990e7f033..0000000000000 --- a/compiler/rustc_baked_icu_data/src/lib.rs +++ /dev/null @@ -1,53 +0,0 @@ -//! This crate contains pre-baked ICU4X data, generated by `icu4x-datagen`. The tool -//! fetches locale data from CLDR and transforms them into const code in statics that -//! ICU4X can load, via databake. `lib.rs` in this crate is manually written, but all -//! other code is generated. -//! -//! This crate can be regenerated when there's a new CLDR version, though that is unlikely -//! to result in changes in most cases (currently this only covers list formatting data, which -//! is rather stable). It may need to be regenerated when updating ICU4X versions, especially -//! across major versions, in case it fails to compile after an update. -//! -//! It must be regenerated when adding new locales to Rust, or if Rust's usage of ICU4X -//! grows to need more kinds of data. -//! -//! To regenerate the data, run this command: -//! -//! ```text -//! icu4x-datagen -W --pretty --use-separate-crates \ -//! --format baked --locales @en @es @fr @it @ja @pt @ru @tr @zh @zh-Hans @zh-Hant \ -//! -m ListAndV1 -o src/data -//! ``` - -// tidy-alphabetical-start -#![allow(elided_lifetimes_in_paths)] -#![allow(unreachable_pub)] // because this crate is mostly generated code -// #![warn(unreachable_pub)] // don't use because this crate is mostly generated code -// tidy-alphabetical-end - -pub struct BakedDataProvider; - -include!("data/mod.rs"); -const _: () = { - impl_data_provider!(BakedDataProvider); -}; - -pub const fn baked_data_provider() -> BakedDataProvider { - BakedDataProvider -} - -pub mod supported_locales { - use icu_locale_core::{Locale, locale}; - use icu_provider::prelude::*; - - pub const EN: Locale = locale!("en"); - pub const ES: Locale = locale!("es"); - pub const FR: Locale = locale!("fr"); - pub const IT: Locale = locale!("it"); - pub const JA: Locale = locale!("ja"); - pub const PT: Locale = locale!("pt"); - pub const RU: Locale = locale!("ru"); - pub const TR: Locale = locale!("tr"); - pub const ZH_HANS: Locale = locale!("zh-Hans"); - pub const ZH_HANT: Locale = locale!("zh-Hant"); -} diff --git a/compiler/rustc_codegen_llvm/src/builder.rs b/compiler/rustc_codegen_llvm/src/builder.rs index 001eb678cebbd..2f57ecdaa6f19 100644 --- a/compiler/rustc_codegen_llvm/src/builder.rs +++ b/compiler/rustc_codegen_llvm/src/builder.rs @@ -1842,10 +1842,6 @@ impl<'a, 'll, CX: Borrow>> GenericBuilder<'a, 'll, CX> { Cow::Owned(casted_args) } - - pub(crate) fn va_arg(&mut self, list: Value<'ll>, ty: Type<'ll>) -> Value<'ll> { - unsafe { llvm::LLVMBuildVAArg(self.llbuilder(), list, ty, UNNAMED) } - } } impl<'a, 'll, 'tcx> Builder<'a, 'll, 'tcx> { diff --git a/compiler/rustc_codegen_llvm/src/va_arg.rs b/compiler/rustc_codegen_llvm/src/va_arg.rs index 997c1efe37776..19d13efdfd223 100644 --- a/compiler/rustc_codegen_llvm/src/va_arg.rs +++ b/compiler/rustc_codegen_llvm/src/va_arg.rs @@ -1313,17 +1313,19 @@ pub(super) fn emit_va_arg<'ll, 'tcx>( AllowHigherAlign::No, ForceRightAdjust::No, ), + Arch::M68k => emit_ptr_va_arg( + bx, + addr, + layout, + PassMode::Direct, + SlotSize::Bytes4, + AllowHigherAlign::No, + ForceRightAdjust::Yes, + ), Arch::Bpf => bug!("bpf does not support c-variadic functions"), Arch::SpirV => bug!("spirv does not support c-variadic functions"), - Arch::M68k => { - std::assert_matches!(stability, CVariadicStatus::Unstable { .. }); - - // Clang uses the LLVM implementation for these architectures. - bx.va_arg(addr.immediate(), layout.llvm_type(bx.cx)) - } - Arch::Other(ref arch) => { std::assert_matches!(stability, CVariadicStatus::Unstable { .. }); diff --git a/compiler/rustc_const_eval/src/const_eval/type_info.rs b/compiler/rustc_const_eval/src/const_eval/type_info.rs index 0f5603e1a0b09..b31fb5904e7d1 100644 --- a/compiler/rustc_const_eval/src/const_eval/type_info.rs +++ b/compiler/rustc_const_eval/src/const_eval/type_info.rs @@ -7,6 +7,7 @@ use rustc_attr_ir::AttrItem; use rustc_attr_ir::Attribute::Tool; use rustc_attr_ir::lang_items::LangItem; use rustc_hir::intravisit::HirTyCtxt; +use rustc_lint_defs::{Reflectiveness, ToolOptions}; use rustc_middle::ty::layout::{HasTyCtxt, TyAndLayout}; use rustc_middle::ty::{self, FnHeader, FnSigKind, FnSigTys, ScalarInt, Ty, TyCtxt}; use rustc_span::{Symbol, span_bug, sym}; @@ -364,8 +365,10 @@ impl<'tcx> InterpCx<'tcx, CompileTimeMachine<'tcx>> { let attrs: Vec<_> = attrs .iter() .filter_map(|attr| { - if let Tool(a_itm @ AttrItem { .. }) = attr - && a_itm.path.segments.first() == Some(&sym::reflection_placeholder) + if let Tool { + item: a_itm @ AttrItem { .. }, + opts: ToolOptions { reflectiveness: Reflectiveness::Reflective, .. }, + } = attr { Some(rustc_hir_pretty::attritem_to_string( &(&self.tcx() as &dyn HirTyCtxt<'_>), diff --git a/compiler/rustc_error_messages/Cargo.toml b/compiler/rustc_error_messages/Cargo.toml index 02851a2255a87..eaa0bebab0401 100644 --- a/compiler/rustc_error_messages/Cargo.toml +++ b/compiler/rustc_error_messages/Cargo.toml @@ -6,10 +6,6 @@ edition = "2024" [dependencies] # tidy-alphabetical-start fluent-bundle = "0.16" -icu_list = { version = "2.3", default-features = false, features = ["alloc"] } -icu_locale_core = { version = "2.3", default-features = false } -intl-memoizer = "0.5.1" -rustc_baked_icu_data = { path = "../rustc_baked_icu_data" } rustc_data_structures = { path = "../rustc_data_structures" } rustc_macros = { path = "../rustc_macros" } rustc_serialize = { path = "../rustc_serialize" } diff --git a/compiler/rustc_error_messages/src/lib.rs b/compiler/rustc_error_messages/src/lib.rs index 881f11ff17b0a..0628efbf9e38d 100644 --- a/compiler/rustc_error_messages/src/lib.rs +++ b/compiler/rustc_error_messages/src/lib.rs @@ -228,73 +228,22 @@ impl From> for MultiSpan { } } -fn icu_locale_from_unic_langid(lang: LanguageIdentifier) -> Option { - icu_locale_core::Locale::try_from_str(&lang.to_string()).ok() -} - pub fn fluent_value_from_str_list_sep_by_and(l: Vec>) -> FluentValue<'_> { - // Fluent requires 'static value here for its AnyEq usages. - #[derive(Clone, PartialEq, Debug)] - struct FluentStrListSepByAnd(Vec); - - impl FluentType for FluentStrListSepByAnd { - fn duplicate(&self) -> Box { - Box::new(self.clone()) - } - - fn as_string(&self, intls: &intl_memoizer::IntlLangMemoizer) -> Cow<'static, str> { - let result = intls - .with_try_get::((), |list_formatter| { - list_formatter.format_to_string(self.0.iter()) - }) - .unwrap(); - Cow::Owned(result) - } - - fn as_string_threadsafe( - &self, - intls: &intl_memoizer::concurrent::IntlLangMemoizer, - ) -> Cow<'static, str> { - let result = intls - .with_try_get::((), |list_formatter| { - list_formatter.format_to_string(self.0.iter()) - }) - .unwrap(); - Cow::Owned(result) - } - } - - struct MemoizableListFormatter(icu_list::ListFormatter); - - impl std::ops::Deref for MemoizableListFormatter { - type Target = icu_list::ListFormatter; - fn deref(&self) -> &Self::Target { - &self.0 - } - } - - impl intl_memoizer::Memoizable for MemoizableListFormatter { - type Args = (); - type Error = (); - - fn construct(lang: LanguageIdentifier, _args: Self::Args) -> Result { - let locale = icu_locale_from_unic_langid(lang) - .unwrap_or_else(|| rustc_baked_icu_data::supported_locales::EN); - let list_formatter = icu_list::ListFormatter::try_new_and_unstable( - &rustc_baked_icu_data::BakedDataProvider, - locale.into(), - icu_list::options::ListFormatterOptions::default() - .with_length(icu_list::options::ListLength::Wide), - ) - .expect("Failed to create list formatter"); - - Ok(MemoizableListFormatter(list_formatter)) + FluentValue::String(match l.as_slice() { + [] => String::new().into(), + [single] => single.clone(), + [first, second] => format!("{first} and {second}").into(), + [multiple @ .., last] => { + let mut s = String::new(); + for i in multiple { + s.push_str(i); + s.push_str(", "); + } + s.push_str("and "); + s.push_str(last); + s.into() } - } - - let l = l.into_iter().map(|x| x.into_owned()).collect(); - - FluentValue::Custom(Box::new(FluentStrListSepByAnd(l))) + }) } /// Simplified version of `FluentArg` that can implement `Encodable` and `Decodable`. Collection of diff --git a/compiler/rustc_hir_pretty/src/lib.rs b/compiler/rustc_hir_pretty/src/lib.rs index 9bb2b89bfe6bf..3e19351c54fcb 100644 --- a/compiler/rustc_hir_pretty/src/lib.rs +++ b/compiler/rustc_hir_pretty/src/lib.rs @@ -101,7 +101,7 @@ impl<'a> State<'a> { /// actual style of the attribute. fn print_attribute_as_style(&mut self, attr: &Attribute, style: ast::AttrStyle) { match &attr { - Attribute::Tool(unparsed) | Attribute::DeriveHelper(unparsed) => { + Attribute::Tool { item: unparsed, .. } | Attribute::DeriveHelper(unparsed) => { self.print_attritem_as_style(unparsed, style) } Attribute::Parsed(AttributeKind::DocComment { kind, comment, .. }) => { diff --git a/compiler/rustc_hir_typeck/src/errors.rs b/compiler/rustc_hir_typeck/src/errors.rs new file mode 100644 index 0000000000000..ee71424eb744b --- /dev/null +++ b/compiler/rustc_hir_typeck/src/errors.rs @@ -0,0 +1,1316 @@ +// ignore-tidy-file-filelength +// FIXME: we should move the field error reporting code somewhere else. + +//! Type checking expressions. +//! +//! See [`rustc_hir_analysis::check`] for more context on type checking in general. + +use rustc_abi::FieldIdx; +use rustc_attr_ir::lang_items::LangItem; +use rustc_data_structures::fx::{FxHashSet, FxIndexSet}; +use rustc_data_structures::thin_vec::ThinVec; +use rustc_data_structures::unord::UnordMap; +use rustc_errors::codes::*; +use rustc_errors::{ + Applicability, Diag, ErrorGuaranteed, MultiSpan, StashKey, Subdiagnostic, listify, pluralize, + struct_span_code_err, +}; +use rustc_hir as hir; +use rustc_hir::def::{CtorKind, Res}; +use rustc_hir::def_id::DefId; +use rustc_hir::{ExprKind, HirId, is_range_literal}; +use rustc_hir_analysis::diagnostics::NoFieldOnType; +use rustc_hir_analysis::hir_ty_lowering::HirTyLowerer as _; +use rustc_middle::ty::print::{with_forced_trimmed_paths, with_no_trimmed_paths}; +use rustc_middle::ty::{self, GenericArgs, Ty, TypeVisitableExt, fold_regions}; +use rustc_span::edit_distance::find_best_match_for_name; +use rustc_span::{Ident, Span, Symbol, bug, kw, sym}; +use rustc_trait_selection::infer::InferCtxtExt; +use rustc_trait_selection::traits::{self, ObligationCauseCode}; +use tracing::{debug, instrument}; + +use crate::diagnostics::{ + HelpUseLatestEdition, ReturnLikeStatementKind, ReturnStmtOutsideOfFnBody, TypeMismatchFruTypo, +}; +use crate::{FnCtxt, type_error_struct}; + +impl<'a, 'tcx> FnCtxt<'a, 'tcx> { + /// Emit an error because `return` or `become` is used outside of a function body. + /// + /// `expr` is the `return` (`become`) "statement", `kind` is the kind of the statement + /// either `Return` or `Become`. + pub(crate) fn emit_return_outside_of_fn_body( + &self, + expr: &hir::Expr<'_>, + kind: ReturnLikeStatementKind, + ) { + let mut err = ReturnStmtOutsideOfFnBody { + span: expr.span, + encl_body_span: None, + encl_fn_span: None, + statement_kind: kind, + }; + + let encl_item_id = self.tcx.hir_get_parent_item(expr.hir_id); + + if let hir::Node::Item(hir::Item { + kind: hir::ItemKind::Fn { .. }, + span: encl_fn_span, + .. + }) + | hir::Node::TraitItem(hir::TraitItem { + kind: hir::TraitItemKind::Fn(_, hir::TraitFn::Provided(_)), + span: encl_fn_span, + .. + }) + | hir::Node::ImplItem(hir::ImplItem { + kind: hir::ImplItemKind::Fn(..), + span: encl_fn_span, + .. + }) = self.tcx.hir_node_by_def_id(encl_item_id.def_id) + { + // We are inside a function body, so reporting "return statement + // outside of function body" needs an explanation. + + let encl_body_owner_id = self.tcx.hir_enclosing_body_owner(expr.hir_id); + + // If this didn't hold, we would not have to report an error in + // the first place. + assert_ne!(encl_item_id.def_id, encl_body_owner_id); + + let encl_body = self.tcx.hir_body_owned_by(encl_body_owner_id); + + err.encl_body_span = Some(encl_body.value.span); + err.encl_fn_span = Some(*encl_fn_span); + } + + self.dcx().emit_err(err); + } + + pub(crate) fn point_at_return_for_opaque_ty_error( + &self, + errors: &mut ThinVec>, + hir_id: HirId, + span: Span, + return_expr_ty: Ty<'tcx>, + return_span: Span, + ) { + // Don't point at the whole block if it's empty + if span == return_span { + return; + } + for err in errors { + let cause = &mut err.obligation.cause; + if let ObligationCauseCode::OpaqueReturnType(None) = cause.code() { + let new_cause = self.cause( + cause.span, + ObligationCauseCode::OpaqueReturnType(Some((return_expr_ty, hir_id))), + ); + *cause = new_cause; + } + } + } + + /// Report an error for a struct field expression when there are fields which aren't provided. + /// + /// ```text + /// error: missing field `you_can_use_this_field` in initializer of `foo::Foo` + /// --> src/main.rs:8:5 + /// | + /// 8 | foo::Foo {}; + /// | ^^^^^^^^ missing `you_can_use_this_field` + /// + /// error: aborting due to 1 previous error + /// ``` + pub(crate) fn report_missing_fields( + &self, + adt_ty: Ty<'tcx>, + span: Span, + full_span: Span, + remaining_fields: UnordMap, + variant: &'tcx ty::VariantDef, + hir_fields: &'tcx [hir::ExprField<'tcx>], + args: GenericArgs<'tcx>, + ) { + let len = remaining_fields.len(); + + let displayable_field_names: Vec<&str> = + remaining_fields.items().map(|(ident, _)| ident.as_str()).into_sorted_stable_ord(); + + let mut truncated_fields_error = String::new(); + let remaining_fields_names = match &displayable_field_names[..] { + [field1] => format!("`{field1}`"), + [field1, field2] => format!("`{field1}` and `{field2}`"), + [field1, field2, field3] => format!("`{field1}`, `{field2}` and `{field3}`"), + _ => { + truncated_fields_error = + format!(" and {} other field{}", len - 3, pluralize!(len - 3)); + displayable_field_names + .iter() + .take(3) + .map(|n| format!("`{n}`")) + .collect::>() + .join(", ") + } + }; + + let mut err = struct_span_code_err!( + self.dcx(), + span, + E0063, + "missing field{} {}{} in initializer of `{}`", + pluralize!(len), + remaining_fields_names, + truncated_fields_error, + adt_ty + ); + err.span_label(span, format!("missing {remaining_fields_names}{truncated_fields_error}")); + + if remaining_fields.items().all(|(_, (_, field))| field.value.is_some()) + && self.tcx.sess.is_nightly_build() + { + let msg = format!( + "all remaining fields have default values, {you_can} use those values with `..`", + you_can = if self.tcx.features().default_field_values() { + "you can" + } else { + "if you added `#![feature(default_field_values)]` to your crate you could" + }, + ); + if let Some(hir_field) = hir_fields.last() { + err.span_suggestion_verbose( + hir_field.span.shrink_to_hi(), + msg, + ", ..".to_string(), + Applicability::MachineApplicable, + ); + } else if hir_fields.is_empty() { + err.span_suggestion_verbose( + span.shrink_to_hi().with_hi(full_span.hi()), + msg, + " { .. }".to_string(), + Applicability::MachineApplicable, + ); + } + } + + if let Some(hir_field) = hir_fields.last() { + self.suggest_fru_from_range_and_emit(hir_field, variant, args, err); + } else { + err.emit(); + } + } + + /// If the last field is a range literal, but it isn't supposed to be, then they probably + /// meant to use functional update syntax. + pub(crate) fn suggest_fru_from_range_and_emit( + &self, + last_expr_field: &hir::ExprField<'tcx>, + variant: &ty::VariantDef, + args: GenericArgs<'tcx>, + mut err: Diag<'_>, + ) { + if is_range_literal(last_expr_field.expr) + && let ExprKind::Struct(&qpath, [range_start, range_end], _) = last_expr_field.expr.kind + && self.tcx.qpath_is_lang_item(qpath, LangItem::Range) + && let variant_field = + variant.fields.iter().find(|field| field.ident(self.tcx) == last_expr_field.ident) + && let range_def_id = self.tcx.lang_items().range_struct() + && variant_field + .and_then(|field| field.ty(self.tcx, args).skip_norm_wip().ty_adt_def()) + .map(|adt| adt.did()) + != range_def_id + { + // Use a (somewhat arbitrary) filtering heuristic to avoid printing + // expressions that are either too long, or have control character + // such as newlines in them. + let expr = self + .tcx + .sess + .source_map() + .span_to_snippet(range_end.expr.span) + .ok() + .filter(|s| s.len() < 25 && !s.contains(|c: char| c.is_control())); + + let fru_span = self + .tcx + .sess + .source_map() + .span_extend_while_whitespace(range_start.expr.span) + .shrink_to_hi() + .to(range_end.expr.span); + + err.subdiagnostic(TypeMismatchFruTypo { + expr_span: range_start.expr.span, + fru_span, + expr, + }); + + // Suppress any range expr type mismatches + self.dcx().try_steal_replace_and_emit_err( + last_expr_field.span, + StashKey::MaybeFruTypo, + err, + ); + } else { + err.emit(); + } + } + + /// Report an error for a struct field expression when there are invisible fields. + /// + /// ```text + /// error: cannot construct `Foo` with struct literal syntax due to private fields + /// --> src/main.rs:8:5 + /// | + /// 8 | foo::Foo {}; + /// | ^^^^^^^^ + /// + /// error: aborting due to 1 previous error + /// ``` + pub(crate) fn report_private_fields( + &self, + adt_ty: Ty<'tcx>, + span: Span, + expr_span: Span, + private_fields: Vec<&ty::FieldDef>, + used_fields: &'tcx [hir::ExprField<'tcx>], + ) { + let mut err = + self.dcx().struct_span_err( + span, + format!( + "cannot construct `{adt_ty}` with struct literal syntax due to private fields", + ), + ); + let (used_private_fields, remaining_private_fields): ( + Vec<(Symbol, Span, bool)>, + Vec<(Symbol, Span, bool)>, + ) = private_fields + .iter() + .map(|field| { + match used_fields.iter().find(|used_field| field.name == used_field.ident.name) { + Some(used_field) => (field.name, used_field.span, true), + None => (field.name, self.tcx.def_span(field.did), false), + } + }) + .partition(|field| field.2); + err.span_labels(used_private_fields.iter().map(|(_, span, _)| *span), "private field"); + + if let ty::Adt(def, _) = adt_ty.kind() { + if (def.did().is_local() || !used_fields.is_empty()) + && !remaining_private_fields.is_empty() + { + let names = if remaining_private_fields.len() > 6 { + String::new() + } else { + format!( + "{} ", + listify(&remaining_private_fields, |(name, _, _)| format!("`{name}`")) + .expect("expected at least one private field to report") + ) + }; + err.note(format!( + "{}private field{s} {names}that {were} not provided", + if used_fields.is_empty() { "" } else { "...and other " }, + s = pluralize!(remaining_private_fields.len()), + were = pluralize!("was", remaining_private_fields.len()), + )); + } + + let def_id = def.did(); + let mut items = self + .tcx + .inherent_impls(def_id) + .into_iter() + .flat_map(|&i| self.tcx.associated_items(i).in_definition_order()) + // Only assoc fn with no receivers. + .filter(|item| item.is_fn() && !item.is_method()) + .filter_map(|item| { + // Only assoc fns that return `Self` + let fn_sig = self + .tcx + .fn_sig(item.def_id) + .instantiate(self.tcx, self.fresh_args_for_item(span, item.def_id)) + .skip_norm_wip(); + let ret_ty = self.tcx.instantiate_bound_regions_with_erased(fn_sig.output()); + if !self.can_eq(self.param_env, ret_ty, adt_ty) { + return None; + } + let input_len = fn_sig.inputs().skip_binder().len(); + let name = item.name(); + let order = !name.as_str().starts_with("new"); + Some((order, name, input_len)) + }) + .collect::>(); + items.sort_by_key(|(order, _, _)| *order); + let suggestion = |name, args| { + format!( + "::{name}({})", + std::iter::repeat_n("_", args).collect::>().join(", ") + ) + }; + match &items[..] { + [] => {} + [(_, name, args)] => { + err.span_suggestion_verbose( + span.shrink_to_hi().with_hi(expr_span.hi()), + format!("you might have meant to use the `{name}` associated function"), + suggestion(name, *args), + Applicability::MaybeIncorrect, + ); + } + _ => { + err.span_suggestions( + span.shrink_to_hi().with_hi(expr_span.hi()), + "you might have meant to use an associated function to build this type", + items.iter().map(|(_, name, args)| suggestion(name, *args)), + Applicability::MaybeIncorrect, + ); + } + } + if let Some(default_trait) = self.tcx.get_diagnostic_item(sym::Default) + && self + .infcx + .type_implements_trait(default_trait, [adt_ty], self.param_env) + .may_apply() + { + err.multipart_suggestion( + "consider using the `Default` trait", + vec![ + (span.shrink_to_lo(), "<".to_string()), + ( + span.shrink_to_hi().with_hi(expr_span.hi()), + " as std::default::Default>::default()".to_string(), + ), + ], + Applicability::MaybeIncorrect, + ); + } + } + + err.emit(); + } + + pub(crate) fn report_unknown_field( + &self, + ty: Ty<'tcx>, + variant: &'tcx ty::VariantDef, + expr: &hir::Expr<'_>, + field: &hir::ExprField<'_>, + skip_fields: &[hir::ExprField<'_>], + kind_name: &str, + ) -> ErrorGuaranteed { + // we don't care to report errors for a struct if the struct itself is tainted + if let Err(guar) = variant.has_errors() { + return guar; + } + let mut err = self.err_ctxt().type_error_struct_with_diag( + field.ident.span, + |actual| match ty.kind() { + ty::Adt(adt, ..) if adt.is_enum() => struct_span_code_err!( + self.dcx(), + field.ident.span, + E0559, + "{} `{}::{}` has no field named `{}`", + kind_name, + actual, + variant.name, + field.ident + ), + _ => struct_span_code_err!( + self.dcx(), + field.ident.span, + E0560, + "{} `{}` has no field named `{}`", + kind_name, + actual, + field.ident + ), + }, + ty, + ); + + let variant_ident_span = self.tcx.def_ident_span(variant.def_id).unwrap(); + match variant.ctor { + Some((CtorKind::Fn, def_id)) => match ty.kind() { + ty::Adt(adt, ..) if adt.is_enum() => { + err.span_context(self.tcx.def_span(adt.did()).shrink_to_lo()); + err.span_label( + variant_ident_span, + format!( + "`{adt}::{variant}` defined here", + adt = ty, + variant = variant.name, + ), + ); + err.span_label(field.ident.span, "field does not exist"); + let fn_sig = self.tcx.fn_sig(def_id).instantiate_identity().skip_norm_wip(); + let inputs = fn_sig.inputs().skip_binder(); + let fields = format!( + "({})", + inputs.iter().map(|i| format!("/* {i} */")).collect::>().join(", ") + ); + let (replace_span, sugg) = match expr.kind { + hir::ExprKind::Struct(qpath, ..) => { + (qpath.span().shrink_to_hi().with_hi(expr.span.hi()), fields) + } + _ => { + (expr.span, format!("{ty}::{variant}{fields}", variant = variant.name)) + } + }; + err.span_suggestion_verbose( + replace_span, + format!( + "`{adt}::{variant}` is a tuple {kind_name}, use the appropriate syntax", + adt = ty, + variant = variant.name, + ), + sugg, + Applicability::HasPlaceholders, + ); + } + _ => { + err.span_label(variant_ident_span, format!("`{ty}` defined here")); + err.span_label(field.ident.span, "field does not exist"); + let fn_sig = self.tcx.fn_sig(def_id).instantiate_identity().skip_norm_wip(); + let inputs = fn_sig.inputs().skip_binder(); + let fields = format!( + "({})", + inputs.iter().map(|i| format!("/* {i} */")).collect::>().join(", ") + ); + err.span_suggestion_verbose( + expr.span, + format!("`{ty}` is a tuple {kind_name}, use the appropriate syntax",), + format!("{ty}{fields}"), + Applicability::HasPlaceholders, + ); + } + }, + _ => { + // prevent all specified fields from being suggested + let available_field_names = self.available_field_names(variant, expr, skip_fields); + if let Some(field_name) = + find_best_match_for_name(&available_field_names, field.ident.name, None) + && !(field.ident.name.as_str().parse::().is_ok() + && field_name.as_str().parse::().is_ok()) + { + err.span_label(field.ident.span, "unknown field"); + err.span_suggestion_verbose( + field.ident.span, + "a field with a similar name exists", + field_name, + Applicability::MaybeIncorrect, + ); + } else { + match ty.kind() { + ty::Adt(adt, ..) => { + if adt.is_enum() { + err.span_label( + field.ident.span, + format!("`{}::{}` does not have this field", ty, variant.name), + ); + } else { + err.span_label( + field.ident.span, + format!("`{ty}` does not have this field"), + ); + } + if available_field_names.is_empty() { + err.note("all struct fields are already assigned"); + } else { + err.note(format!( + "available fields are: {}", + self.name_series_display(available_field_names) + )); + } + } + _ => bug!("non-ADT passed to report_unknown_field"), + } + }; + } + } + err.emit_err() + } + + fn name_series_display(&self, names: Vec) -> String { + // dynamic limit, to never omit just one field + let limit = if names.len() == 6 { 6 } else { 5 }; + let mut display = + names.iter().take(limit).map(|n| format!("`{n}`")).collect::>().join(", "); + if names.len() > limit { + display = format!("{} ... and {} others", display, names.len() - limit); + } + display + } + + fn suggest_await_on_field_access( + &self, + err: &mut Diag<'_>, + field_ident: Ident, + base: &'tcx hir::Expr<'tcx>, + ty: Ty<'tcx>, + ) { + let Some(output_ty) = self.tcx.get_impl_future_output_ty(ty) else { + err.span_label(field_ident.span, "unknown field"); + return; + }; + let ty::Adt(def, _) = output_ty.kind() else { + err.span_label(field_ident.span, "unknown field"); + return; + }; + // no field access on enum type + if def.is_enum() { + err.span_label(field_ident.span, "unknown field"); + return; + } + if !def.non_enum_variant().fields.iter().any(|field| field.ident(self.tcx) == field_ident) { + err.span_label(field_ident.span, "unknown field"); + return; + } + err.span_label( + field_ident.span, + "field not available in `impl Future`, but it is available in its `Output`", + ); + match self.tcx.coroutine_kind(self.body_def_id) { + Some(hir::CoroutineKind::Desugared(hir::CoroutineDesugaring::Async, _)) => { + err.span_suggestion_verbose( + base.span.shrink_to_hi(), + "consider `await`ing on the `Future` to access the field", + ".await", + Applicability::MaybeIncorrect, + ); + } + _ => { + let mut span: MultiSpan = base.span.into(); + span.push_span_label(self.tcx.def_span(self.body_def_id), "this is not `async`"); + err.span_note( + span, + "this implements `Future` and its output type has the field, \ + but the future cannot be awaited in a synchronous function", + ); + } + } + } + + pub(crate) fn ban_nonexisting_field( + &self, + ident: Ident, + base: &'tcx hir::Expr<'tcx>, + expr: &'tcx hir::Expr<'tcx>, + base_ty: Ty<'tcx>, + ) -> ErrorGuaranteed { + debug!( + "ban_nonexisting_field: field={:?}, base={:?}, expr={:?}, base_ty={:?}", + ident, base, expr, base_ty + ); + let mut err = self.no_such_field_err(ident, base_ty, expr); + + match *base_ty.peel_refs().kind() { + ty::Array(_, len) => { + self.maybe_suggest_array_indexing(&mut err, base, ident, len); + } + ty::RawPtr(..) => { + self.suggest_first_deref_field(&mut err, base, ident); + } + ty::Param(param_ty) => { + err.span_label(ident.span, "unknown field"); + self.point_at_param_definition(&mut err, param_ty); + } + ty::Alias(_, ty::AliasTy { kind: ty::Opaque { .. }, .. }) => { + self.suggest_await_on_field_access(&mut err, ident, base, base_ty.peel_refs()); + } + _ => { + err.span_label(ident.span, "unknown field"); + } + } + + self.suggest_fn_call(&mut err, base, base_ty, |output_ty| { + if let ty::Adt(def, _) = output_ty.kind() + && !def.is_enum() + { + def.non_enum_variant().fields.iter().any(|field| { + field.ident(self.tcx) == ident + && field.vis.is_accessible_from(expr.hir_id.owner.def_id, self.tcx) + }) + } else if let ty::Tuple(tys) = output_ty.kind() + && let Ok(idx) = ident.as_str().parse::() + { + idx < tys.len() + } else { + false + } + }); + + if ident.name == kw::Await { + // We know by construction that `.await` is either on Rust 2015 + // or results in `ExprKind::Await`. Suggest switching the edition to 2018. + err.note("to `.await` a `Future`, switch to Rust 2018 or later"); + HelpUseLatestEdition::new().add_to_diag(&mut err); + } + + err.emit_err() + } + + pub(crate) fn ban_private_field_access( + &self, + expr: &hir::Expr<'tcx>, + expr_t: Ty<'tcx>, + field: Ident, + base_did: DefId, + return_ty: Option>, + ) -> ErrorGuaranteed { + let mut err = self.private_field_err(field, base_did); + + // Also check if an accessible method exists, which is often what is meant. + if self.method_exists_for_diagnostic(field, expr_t, expr.hir_id, return_ty) + && !self.expr_in_place(expr.hir_id) + { + self.suggest_method_call( + &mut err, + format!("a method `{field}` also exists, call it with parentheses"), + field, + expr_t, + expr, + None, + ); + } + err.emit_err() + } + + pub(crate) fn ban_take_value_of_method( + &self, + expr: &hir::Expr<'tcx>, + expr_t: Ty<'tcx>, + field: Ident, + ) -> ErrorGuaranteed { + let mut err = type_error_struct!( + self.dcx(), + field.span, + expr_t, + E0615, + "attempted to take value of method `{field}` on type `{expr_t}`", + ); + err.span_label(field.span, "method, not a field"); + let expr_is_call = + if let hir::Node::Expr(hir::Expr { kind: ExprKind::Call(callee, _args), .. }) = + self.tcx.parent_hir_node(expr.hir_id) + { + expr.hir_id == callee.hir_id + } else { + false + }; + let expr_snippet = + self.tcx.sess.source_map().span_to_snippet(expr.span).unwrap_or_default(); + let is_wrapped = expr_snippet.starts_with('(') && expr_snippet.ends_with(')'); + let after_open = expr.span.lo() + rustc_span::BytePos(1); + let before_close = expr.span.hi() - rustc_span::BytePos(1); + + if expr_is_call && is_wrapped { + err.multipart_suggestion( + "remove wrapping parentheses to call the method", + vec![ + (expr.span.with_hi(after_open), String::new()), + (expr.span.with_lo(before_close), String::new()), + ], + Applicability::MachineApplicable, + ); + } else if !self.expr_in_place(expr.hir_id) { + // Suggest call parentheses inside the wrapping parentheses + let span = if is_wrapped { + expr.span.with_lo(after_open).with_hi(before_close) + } else { + expr.span + }; + self.suggest_method_call( + &mut err, + "use parentheses to call the method", + field, + expr_t, + expr, + Some(span), + ); + } else if let ty::RawPtr(ptr_ty, _) = expr_t.kind() + && let ty::Adt(adt_def, _) = ptr_ty.kind() + && let ExprKind::Field(base_expr, _) = expr.kind + && let [variant] = &adt_def.variants().raw + && variant.fields.iter().any(|f| f.ident(self.tcx) == field) + { + err.multipart_suggestion( + "to access the field, dereference first", + vec![ + (base_expr.span.shrink_to_lo(), "(*".to_string()), + (base_expr.span.shrink_to_hi(), ")".to_string()), + ], + Applicability::MaybeIncorrect, + ); + } else { + err.help("methods are immutable and cannot be assigned to"); + } + + // See `StashKey::GenericInFieldExpr` for more info + self.dcx().try_steal_replace_and_emit_err(field.span, StashKey::GenericInFieldExpr, err) + } + + fn point_at_param_definition(&self, err: &mut Diag<'_>, param: ty::ParamTy) { + let generics = self.tcx.generics_of(self.body_def_id); + let generic_param = generics.type_param(param, self.tcx); + if let ty::GenericParamDefKind::Type { synthetic: true, .. } = generic_param.kind { + return; + } + let param_def_id = generic_param.def_id; + let param_hir_id = match param_def_id.as_local() { + Some(x) => self.tcx.local_def_id_to_hir_id(x), + None => return, + }; + let param_span = self.tcx.hir_span(param_hir_id); + let param_name = self.tcx.hir_ty_param_name(param_def_id.expect_local()); + + err.span_label(param_span, format!("type parameter '{param_name}' declared here")); + } + + fn maybe_suggest_array_indexing( + &self, + err: &mut Diag<'_>, + base: &hir::Expr<'_>, + field: Ident, + len: ty::Const<'tcx>, + ) { + err.span_label(field.span, "unknown field"); + if let (Some(len), Ok(user_index)) = ( + self.try_structurally_resolve_const(base.span, len).try_to_target_usize(self.tcx), + field.as_str().parse::(), + ) { + let help = "instead of using tuple indexing, use array indexing"; + let applicability = if len < user_index { + Applicability::MachineApplicable + } else { + Applicability::MaybeIncorrect + }; + err.multipart_suggestion( + help, + vec![ + (base.span.between(field.span), "[".to_string()), + (field.span.shrink_to_hi(), "]".to_string()), + ], + applicability, + ); + } + } + + fn suggest_first_deref_field(&self, err: &mut Diag<'_>, base: &hir::Expr<'_>, field: Ident) { + err.span_label(field.span, "unknown field"); + if base.span.from_expansion() || field.span.from_expansion() { + return; + } + let val = if let Ok(base) = self.tcx.sess.source_map().span_to_snippet(base.span) + && base.len() < 20 + { + format!("`{base}`") + } else { + "the value".to_string() + }; + err.multipart_suggestion( + format!("{val} is a raw pointer; try dereferencing it"), + vec![ + (base.span.shrink_to_lo(), "(*".into()), + (base.span.between(field.span), format!(").")), + ], + Applicability::MaybeIncorrect, + ); + } + + pub(crate) fn no_such_field_err( + &self, + field: Ident, + base_ty: Ty<'tcx>, + expr: &hir::Expr<'tcx>, + ) -> Diag<'_> { + let span = field.span; + debug!("no_such_field_err(span: {:?}, field: {:?}, expr_t: {:?})", span, field, base_ty); + + let mut err = self.dcx().create_err(NoFieldOnType { span, ty: base_ty, field }); + if base_ty.references_error() { + err.downgrade_to_delayed_bug(); + } + + self.detect_shadowed_method_on_incorrect_field_access(&mut err, field, base_ty, expr); + + if let Some(within_macro_span) = span.within_macro(expr.span, self.tcx.sess.source_map()) { + err.span_label(within_macro_span, "due to this macro variable"); + } + + // Check if there is an associated function with the same name. + if let Some(def_id) = base_ty.peel_refs().ty_adt_def().map(|d| d.did()) { + for &impl_def_id in self.tcx.inherent_impls(def_id) { + for item in self.tcx.associated_items(impl_def_id).in_definition_order() { + if let ExprKind::Field(base_expr, _) = expr.kind + && item.name() == field.name + && matches!(item.kind, ty::AssocKind::Fn { has_self: false, .. }) + { + err.span_label(field.span, "this is an associated function, not a method"); + err.note("found the following associated function; to be used as method, it must have a `self` parameter"); + let impl_ty = + self.tcx.type_of(impl_def_id).instantiate_identity().skip_norm_wip(); + err.span_note( + self.tcx.def_span(item.def_id), + format!("the candidate is defined in an impl for the type `{impl_ty}`"), + ); + + let ty_str = match base_ty.peel_refs().kind() { + ty::Adt(def, args) => self.tcx.def_path_str_with_args(def.did(), *args), + _ => base_ty.peel_refs().to_string(), + }; + err.multipart_suggestion( + "use associated function syntax instead", + vec![ + (base_expr.span, ty_str), + (base_expr.span.between(field.span), "::".to_string()), + ], + Applicability::MaybeIncorrect, + ); + return err; + } + } + } + } + + // try to add a suggestion in case the field is a nested field of a field of the Adt + let (ty, unwrap) = if let ty::Adt(def, args) = base_ty.kind() + && (self.tcx.is_diagnostic_item(sym::Result, def.did()) + || self.tcx.is_diagnostic_item(sym::Option, def.did())) + && let Some(arg) = args.get(0) + && let Some(ty) = arg.as_type() + { + (ty, "unwrap().") + } else { + (base_ty, "") + }; + for found_fields in self.get_field_candidates_considering_privacy_for_diag(span, ty) { + let field_names = found_fields.iter().map(|field| field.0.name).collect::>(); + let mut candidate_fields: Vec<_> = found_fields + .into_iter() + .filter_map(|candidate_field| { + self.check_for_nested_field_satisfying_condition_for_diag( + span, + &|candidate_field, _| candidate_field == field, + candidate_field, + vec![], + ) + }) + .map(|mut field_path| { + field_path.pop(); + field_path.iter().map(|id| format!("{}.", id)).collect::() + }) + .collect::>(); + candidate_fields.sort(); + + let len = candidate_fields.len(); + // Don't suggest `.field` if the base expr is from a different + // syntax context than the field. + if len > 0 && expr.span.ctxt() == field.span.ctxt() { + err.span_suggestions( + field.span.shrink_to_lo(), + format!( + "{} of the expressions' fields {} a field of the same name", + if len > 1 { "some" } else { "one" }, + if len > 1 { "have" } else { "has" }, + ), + candidate_fields.iter().map(|path| format!("{unwrap}{path}")), + Applicability::MaybeIncorrect, + ); + } else if let Some(field_name) = + find_best_match_for_name(&field_names, field.name, None) + && !(field.name.as_str().parse::().is_ok() + && field_name.as_str().parse::().is_ok()) + { + err.span_suggestion_verbose( + field.span, + "a field with a similar name exists", + format!("{unwrap}{}", field_name), + Applicability::MaybeIncorrect, + ); + } else if !field_names.is_empty() { + let is = if field_names.len() == 1 { " is" } else { "s are" }; + err.note( + format!("available field{is}: {}", self.name_series_display(field_names),), + ); + } + } + err + } + + fn detect_shadowed_method_on_incorrect_field_access( + &self, + err: &mut Diag<'_>, + field: Ident, + base_ty: Ty<'tcx>, + expr: &hir::Expr<'tcx>, + ) { + let hir::ExprKind::Field(expr, ..) = expr.kind else { return }; + self.find_shadowed_method_and_provide_diagnostic_context(err, base_ty, expr, |ty| { + // Does the alternative method call's resulting type auto-deref to a type that has + // the field the user is trying to access? + self.get_field_candidates_considering_privacy_for_diag(expr.span, ty) + .into_iter() + .flat_map(|fields| fields.into_iter()) + .find(|(f, _ty)| f.name == field.name) + .is_some() + }); + } + + pub(crate) fn all_methods( + &self, + method_ident: Ident, + ty: Ty<'tcx>, + ) -> impl Iterator { + let mut impls: Vec<_> = self + .tcx + .all_traits_including_private() + .filter(|trait_def_id| { + // Consider only traits with the associated type + self.tcx + .associated_items(*trait_def_id) + .in_definition_order() + .any(|i| i.is_method() && i.ident(self.tcx).name == method_ident.name) + && self.tcx.all_impls(*trait_def_id).any(|impl_def_id| { + let header = self.tcx.impl_trait_header(impl_def_id); + let trait_ref = header + .trait_ref + .instantiate( + self.tcx, + self.infcx.fresh_args_for_item(method_ident.span, impl_def_id), + ) + .skip_norm_wip(); + let value = fold_regions(self.tcx, ty, |_, _| self.tcx.lifetimes.re_erased); + if value.has_escaping_bound_vars() { + return false; + } + self.infcx.can_eq(ty::ParamEnv::empty(), trait_ref.self_ty(), value) + && header.polarity != ty::ImplPolarity::Negative + }) + }) + .map(|def_id| (def_id, false)) + .collect(); + if let ty::Adt(def, _args) = ty.kind() { + // Get all the `impl ReceiverType`s. + impls.extend( + self.tcx + .inherent_impls(def.did()) + .into_iter() + .cloned() + .map(|def_id| (def_id, true)), + ); + } + impls.into_iter().filter_map(move |(i, inherent)| { + self.tcx + .associated_items(i) + .in_definition_order() + .find(|assoc| assoc.is_method() && assoc.ident(self.tcx).name == method_ident.name) + .map(|assoc| (i, assoc.def_id, inherent)) + }) + } + + /// Given `expr`, detect if it is a method call that might have been shadowed by another trait + /// being in scope. Only include those traits/impls whose similarly named method have a return + /// type that `finder` considers as "valid" (for example, it has the expected field or method). + pub(crate) fn find_shadowed_method_and_provide_diagnostic_context( + &self, + err: &mut Diag<'_>, + base_ty: Ty<'tcx>, + mut expr: &hir::Expr<'tcx>, + finder: impl Fn(Ty<'tcx>) -> bool, + ) { + if let hir::ExprKind::Unary(hir::UnOp::Deref, e) = expr.kind { + // If we have `*foo`, we want `foo`, which will subsequently be resolved to the earlier + // binding. + expr = e; + } + if let hir::ExprKind::Path(hir::QPath::Resolved( + None, + hir::Path { res: Res::Local(hir_id), .. }, + )) = expr.kind + && let hir::Node::Pat(_) = self.tcx.hir_node(*hir_id) + && let hir::Node::LetStmt(local) = self.tcx.parent_hir_node(*hir_id) + && let Some(binding_expr) = local.init + { + // Get and point at the binding's prior method call, if it is one: + // ``` + // let foo = bar.borrow(); + // foo.qux(); + // ``` + // Where `qux` is present in the return type of `::borrow`, but not + // `::borrow`. + expr = binding_expr; + }; + let hir::ExprKind::MethodCall(segment, rcvr, args, span_with_args) = expr.kind else { + return; + }; + let Some(def_id) = self.typeck_results.borrow().type_dependent_def_id(expr.hir_id) else { + return; + }; + let rcvr_ty = self.typeck_results.borrow().expr_ty_adjusted(rcvr); + let autoderef = self.autoderef(span_with_args, rcvr_ty).silence_errors(); + let mut alternatives = FxIndexSet::default(); + for (ty, _) in autoderef { + // Get all traits that are implemented by the potential autoderefs for the + // receiver for methods with the same name. + let impls = self.all_methods(segment.ident, ty); + // In all the `impl`s for the autoderefs of the receiver type, look for the method + // *except* the one that was actually called. This would end up being an empty set + // if there are no alternatives. + for (parent, def_id, inherent) in impls.filter(|(_, did, _)| def_id != *did) { + let gen_args = if let ty::Adt(_, args) = ty.peel_refs().kind() + && inherent + { + // We want the arguments of the *type* to be passed to the `impl ReceiverType`. + *args + } else { + // We want to use the `ReceiverType` for `Self` on trait impls. + GenericArgs::for_item(self.tcx, def_id, |param, _| { + if let ty::GenericParamDefKind::Lifetime = param.kind { + self.tcx.lifetimes.re_erased.into() + } else if param.name == kw::SelfUpper { + ty.into() + } else { + self.infcx.var_for_def(span_with_args, param) + } + }) + }; + let fn_sig = + self.tcx.fn_sig(def_id).instantiate(self.tcx, gen_args).skip_norm_wip(); + let ret_ty = fn_sig.output(); + let ret_ty = self.tcx.instantiate_bound_regions_with_erased( + self.deeply_resolve_ignoring_regions_with_obligations(ret_ty), + ); + + // Does the alternative method call's resulting type auto-deref to a type that has + // the thing the user is trying to access? + if !finder(ret_ty) { + continue; + } + // It does! We'll point at it and suggest the fully-qualified path to the + // alternative method call. + let mut span: MultiSpan = self.tcx.def_span(def_id).into(); + span.push_span_context(self.tcx.def_span(parent)); + let path = with_no_trimmed_paths!(self.tcx.def_path_str(def_id)); + let after_rcvr = match args { + [] => (rcvr.span.shrink_to_hi().to(span_with_args), ")".to_string()), + [first, ..] => (rcvr.span.shrink_to_hi().to(first.span), ", ".to_string()), + }; + let self_ty = fn_sig.input(0).skip_binder(); + let mutbl = match self_ty.kind() { + ty::Ref(_, _, mutbl) => mutbl.ref_prefix_str(), + _ => "", + }; + // FIXME: in the suggestions we are now (almost) always suggesting the type or trait + // name as if it was already imported, regardless of whether it is. This means that + // a follow up suggestion will be needed if the item is not in scope (which likely + // won't be). + let call = if inherent { + let args = if let ty::Adt(def, args) = ty.peel_refs().kind() { + self.fresh_args_for_item(expr.span, parent).rebase_onto( + self.tcx, + def.did(), + *args, + ) + } else { + self.fresh_args_for_item(expr.span, def_id) + }; + // `Type::method(&rcvr)` + with_forced_trimmed_paths!(format!( + "{}({mutbl}", + self.tcx.value_path_str_with_args(def_id, args), + )) + } else { + // `<_ as Trait>::method(&rcvr)` + format!( + "<_ as {}>::{}({mutbl}", + with_forced_trimmed_paths!(self.tcx.def_path_str_with_args( + parent, + self.fresh_args_for_item(expr.span, parent) + )), + segment.ident + ) + }; + let sugg = vec![(rcvr.span.shrink_to_lo(), call), after_rcvr]; + alternatives.insert((path, span, sugg)); + } + } + if alternatives.is_empty() { + return; + } + let path = with_no_trimmed_paths!(self.tcx.def_path_str(def_id)); + + // On the main diagnostic, point at the method call before the field access to make it clear + // what it actually was. + err.span_label(segment.ident.span, format!("this method is `{path}`")); + + // Point at the method definition, including its impl or trait, being explicit about what + // type it returns, which at this point we know doesn't have the desired field. + let base_ty = self.tcx.short_string(base_ty, err.long_ty_path()); + let mut span: MultiSpan = self.tcx.def_span(def_id).into(); + span.push_span_context(self.tcx.def_span(self.tcx.parent(def_id))); + err.span_note(span, format!("this returns `{base_ty}`")); + + for (path, span, sugg) in alternatives { + // Show the alternatives' method definition... + err.span_note(span, format!("you might have meant to call `{path}` instead")); + // ...and suggest the fully-qualified path to call them instead. + err.multipart_suggestion( + format!("consider calling `{path}` using the fully-qualified path"), + sugg, + Applicability::MaybeIncorrect, + ); + } + } + + pub(crate) fn private_field_err(&self, field: Ident, base_did: DefId) -> Diag<'_> { + let struct_path = self.tcx().def_path_str(base_did); + let kind_name = self.tcx().def_descr(base_did); + struct_span_code_err!( + self.dcx(), + field.span, + E0616, + "field `{field}` of {kind_name} `{struct_path}` is private", + ) + .with_span_label(field.span, "private field") + } + + pub(crate) fn get_field_candidates_considering_privacy_for_diag( + &self, + span: Span, + base_ty: Ty<'tcx>, + ) -> Vec)>> { + debug!("get_field_candidates(span: {:?}, base_t: {:?}", span, base_ty); + + let mut autoderef = self.autoderef(span, base_ty).silence_errors(); + let deref_chain: Vec<_> = autoderef.by_ref().collect(); + + // Don't probe if we hit the recursion limit, since it may result in + // quadratic blowup if we then try to further deref the results of this + // function. This is a best-effort method, after all. + if autoderef.reached_recursion_limit() { + return vec![]; + } + + deref_chain + .into_iter() + .filter_map(move |(base_t, _)| { + match base_t.kind() { + ty::Adt(base_def, args) if !base_def.is_enum() => { + let tcx = self.tcx; + let fields = &base_def.non_enum_variant().fields; + // Some struct, e.g. some that impl `Deref`, have all private fields + // because you're expected to deref them to access the _real_ fields. + // This, for example, will help us suggest accessing a field through a `Box`. + if fields + .iter() + .all(|field| !field.vis.is_accessible_from(self.mod_id, tcx)) + { + return None; + } + return Some( + fields + .iter() + .filter(move |field| { + field.vis.is_accessible_from(self.mod_id, tcx) + && self.is_field_suggestable(field, span) + }) + // For compile-time reasons put a limit on number of fields we search + .take(100) + .map(|field_def| { + ( + field_def.ident(self.tcx).normalize_to_macros_2_0(), + field_def.ty(self.tcx, *args).skip_norm_wip(), + ) + }) + .collect::>(), + ); + } + ty::Tuple(types) => { + return Some( + types + .iter() + .enumerate() + // For compile-time reasons put a limit on number of fields we search + .take(100) + .map(|(i, ty)| (Ident::from_str(&i.to_string()), ty)) + .collect::>(), + ); + } + _ => None, + } + }) + .collect() + } + + /// This method is called after we have encountered a missing field error to recursively + /// search for the field + #[instrument(skip(self, matches), level = "debug")] + pub(crate) fn check_for_nested_field_satisfying_condition_for_diag( + &self, + span: Span, + matches: &impl Fn(Ident, Ty<'tcx>) -> bool, + (candidate_name, candidate_ty): (Ident, Ty<'tcx>), + mut field_path: Vec, + ) -> Option> { + if field_path.len() > 3 { + // For compile-time reasons and to avoid infinite recursion we only check for fields + // up to a depth of three + return None; + } + field_path.push(candidate_name); + if matches(candidate_name, candidate_ty) { + return Some(field_path); + } + for nested_fields in + self.get_field_candidates_considering_privacy_for_diag(span, candidate_ty) + { + // recursively search fields of `candidate_field` if it's a ty::Adt + for field in nested_fields { + if let Some(field_path) = self.check_for_nested_field_satisfying_condition_for_diag( + span, + matches, + field, + field_path.clone(), + ) { + return Some(field_path); + } + } + } + None + } + + pub(crate) fn point_at_index( + &self, + errors: &mut ThinVec>, + span: Span, + ) { + let mut seen_preds = FxHashSet::default(); + // We re-sort here so that the outer most root obligations comes first, as we have the + // subsequent weird logic to identify *every* relevant obligation for proper deduplication + // of diagnostics. + errors.sort_by_key(|error| error.root_obligation.recursion_depth); + for error in errors { + match ( + error.root_obligation.predicate.kind().skip_binder(), + error.obligation.predicate.kind().skip_binder(), + ) { + (ty::PredicateKind::Clause(ty::ClauseKind::Trait(predicate)), _) + if self.tcx.is_lang_item(predicate.trait_ref.def_id, LangItem::Index) => + { + seen_preds.insert(error.obligation.predicate.kind().skip_binder()); + } + (_, ty::PredicateKind::Clause(ty::ClauseKind::Trait(predicate))) + if self.tcx.is_diagnostic_item(sym::SliceIndex, predicate.trait_ref.def_id) => + { + seen_preds.insert(error.obligation.predicate.kind().skip_binder()); + } + (root, pred) if seen_preds.contains(&pred) || seen_preds.contains(&root) => {} + _ => continue, + } + error.obligation.cause.span = span; + } + } +} diff --git a/compiler/rustc_hir_typeck/src/expr.rs b/compiler/rustc_hir_typeck/src/expr.rs index 3c8b4f125ff78..7356f8f94615b 100644 --- a/compiler/rustc_hir_typeck/src/expr.rs +++ b/compiler/rustc_hir_typeck/src/expr.rs @@ -12,19 +12,16 @@ use rustc_ast as ast; use rustc_ast::util::parser::ExprPrecedence; use rustc_attr_ir::find_attr; use rustc_attr_ir::lang_items::LangItem; -use rustc_data_structures::fx::{FxHashMap, FxHashSet}; -use rustc_data_structures::thin_vec::ThinVec; +use rustc_data_structures::fx::FxHashMap; use rustc_data_structures::unord::UnordMap; use rustc_errors::codes::*; use rustc_errors::{ - Applicability, Diag, ErrorGuaranteed, MultiSpan, StashKey, Subdiagnostic, listify, pluralize, - struct_span_code_err, + Applicability, Diag, ErrorGuaranteed, StashKey, listify, pluralize, struct_span_code_err, }; use rustc_hir as hir; -use rustc_hir::def::{CtorKind, DefKind, Res}; -use rustc_hir::def_id::DefId; +use rustc_hir::def::{DefKind, Res}; use rustc_hir::{ExprKind, HirId, QPath, is_range_literal}; -use rustc_hir_analysis::diagnostics::{NoFieldOnType, NoVariantNamed}; +use rustc_hir_analysis::diagnostics::NoVariantNamed; use rustc_hir_analysis::hir_ty_lowering::HirTyLowerer as _; use rustc_infer::infer::{self, RegionVariableOrigin}; use rustc_infer::traits::WellFormedLoc; @@ -33,7 +30,6 @@ use rustc_middle::ty::adjustment::{Adjust, Adjustment, AllowTwoPhase}; use rustc_middle::ty::error::{ExpectedFound, TypeError}; use rustc_middle::ty::{self, AdtKind, ConstKind, GenericArgs, Ty, TypeVisitableExt, Unnormalized}; use rustc_session::diagnostics::feature_err; -use rustc_span::edit_distance::find_best_match_for_name; use rustc_span::hygiene::DesugaringKind; use rustc_span::{Ident, Span, Spanned, Symbol, bug, kw, span_bug, sym}; use rustc_trait_selection::infer::InferCtxtExt; @@ -47,8 +43,7 @@ use crate::diagnostics::{ AddressOfTemporaryTaken, BaseExpressionDoubleDot, BaseExpressionDoubleDotAddExpr, BaseExpressionDoubleDotRemove, CantDereference, DelegationInvalidAdtForReturnWrapping, ExprParenthesesNeeded, FieldMultiplySpecifiedInInitializer, FunctionalRecordUpdateOnNonStruct, - HelpUseLatestEdition, NakedAsmOutsideNakedFn, NoFieldOnVariant, ReturnLikeStatementKind, - ReturnStmtOutsideOfFnBody, StructExprNonExhaustive, TypeMismatchFruTypo, + NakedAsmOutsideNakedFn, NoFieldOnVariant, ReturnLikeStatementKind, StructExprNonExhaustive, YieldExprOutsideOfCoroutine, }; use crate::op::contains_let_in_chain; @@ -1024,78 +1019,6 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { } } - /// Emit an error because `return` or `become` is used outside of a function body. - /// - /// `expr` is the `return` (`become`) "statement", `kind` is the kind of the statement - /// either `Return` or `Become`. - fn emit_return_outside_of_fn_body(&self, expr: &hir::Expr<'_>, kind: ReturnLikeStatementKind) { - let mut err = ReturnStmtOutsideOfFnBody { - span: expr.span, - encl_body_span: None, - encl_fn_span: None, - statement_kind: kind, - }; - - let encl_item_id = self.tcx.hir_get_parent_item(expr.hir_id); - - if let hir::Node::Item(hir::Item { - kind: hir::ItemKind::Fn { .. }, - span: encl_fn_span, - .. - }) - | hir::Node::TraitItem(hir::TraitItem { - kind: hir::TraitItemKind::Fn(_, hir::TraitFn::Provided(_)), - span: encl_fn_span, - .. - }) - | hir::Node::ImplItem(hir::ImplItem { - kind: hir::ImplItemKind::Fn(..), - span: encl_fn_span, - .. - }) = self.tcx.hir_node_by_def_id(encl_item_id.def_id) - { - // We are inside a function body, so reporting "return statement - // outside of function body" needs an explanation. - - let encl_body_owner_id = self.tcx.hir_enclosing_body_owner(expr.hir_id); - - // If this didn't hold, we would not have to report an error in - // the first place. - assert_ne!(encl_item_id.def_id, encl_body_owner_id); - - let encl_body = self.tcx.hir_body_owned_by(encl_body_owner_id); - - err.encl_body_span = Some(encl_body.value.span); - err.encl_fn_span = Some(*encl_fn_span); - } - - self.dcx().emit_err(err); - } - - fn point_at_return_for_opaque_ty_error( - &self, - errors: &mut ThinVec>, - hir_id: HirId, - span: Span, - return_expr_ty: Ty<'tcx>, - return_span: Span, - ) { - // Don't point at the whole block if it's empty - if span == return_span { - return; - } - for err in errors { - let cause = &mut err.obligation.cause; - if let ObligationCauseCode::OpaqueReturnType(None) = cause.code() { - let new_cause = self.cause( - cause.span, - ObligationCauseCode::OpaqueReturnType(Some((return_expr_ty, hir_id))), - ); - *cause = new_cause; - } - } - } - pub(crate) fn check_lhs_assignable( &self, lhs: &'tcx hir::Expr<'tcx>, @@ -2335,429 +2258,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { } } - /// Report an error for a struct field expression when there are fields which aren't provided. - /// - /// ```text - /// error: missing field `you_can_use_this_field` in initializer of `foo::Foo` - /// --> src/main.rs:8:5 - /// | - /// 8 | foo::Foo {}; - /// | ^^^^^^^^ missing `you_can_use_this_field` - /// - /// error: aborting due to 1 previous error - /// ``` - fn report_missing_fields( - &self, - adt_ty: Ty<'tcx>, - span: Span, - full_span: Span, - remaining_fields: UnordMap, - variant: &'tcx ty::VariantDef, - hir_fields: &'tcx [hir::ExprField<'tcx>], - args: GenericArgs<'tcx>, - ) { - let len = remaining_fields.len(); - - let displayable_field_names: Vec<&str> = - remaining_fields.items().map(|(ident, _)| ident.as_str()).into_sorted_stable_ord(); - - let mut truncated_fields_error = String::new(); - let remaining_fields_names = match &displayable_field_names[..] { - [field1] => format!("`{field1}`"), - [field1, field2] => format!("`{field1}` and `{field2}`"), - [field1, field2, field3] => format!("`{field1}`, `{field2}` and `{field3}`"), - _ => { - truncated_fields_error = - format!(" and {} other field{}", len - 3, pluralize!(len - 3)); - displayable_field_names - .iter() - .take(3) - .map(|n| format!("`{n}`")) - .collect::>() - .join(", ") - } - }; - - let mut err = struct_span_code_err!( - self.dcx(), - span, - E0063, - "missing field{} {}{} in initializer of `{}`", - pluralize!(len), - remaining_fields_names, - truncated_fields_error, - adt_ty - ); - err.span_label(span, format!("missing {remaining_fields_names}{truncated_fields_error}")); - - if remaining_fields.items().all(|(_, (_, field))| field.value.is_some()) - && self.tcx.sess.is_nightly_build() - { - let msg = format!( - "all remaining fields have default values, {you_can} use those values with `..`", - you_can = if self.tcx.features().default_field_values() { - "you can" - } else { - "if you added `#![feature(default_field_values)]` to your crate you could" - }, - ); - if let Some(hir_field) = hir_fields.last() { - err.span_suggestion_verbose( - hir_field.span.shrink_to_hi(), - msg, - ", ..".to_string(), - Applicability::MachineApplicable, - ); - } else if hir_fields.is_empty() { - err.span_suggestion_verbose( - span.shrink_to_hi().with_hi(full_span.hi()), - msg, - " { .. }".to_string(), - Applicability::MachineApplicable, - ); - } - } - - if let Some(hir_field) = hir_fields.last() { - self.suggest_fru_from_range_and_emit(hir_field, variant, args, err); - } else { - err.emit(); - } - } - - /// If the last field is a range literal, but it isn't supposed to be, then they probably - /// meant to use functional update syntax. - fn suggest_fru_from_range_and_emit( - &self, - last_expr_field: &hir::ExprField<'tcx>, - variant: &ty::VariantDef, - args: GenericArgs<'tcx>, - mut err: Diag<'_>, - ) { - if is_range_literal(last_expr_field.expr) - && let ExprKind::Struct(&qpath, [range_start, range_end], _) = last_expr_field.expr.kind - && self.tcx.qpath_is_lang_item(qpath, LangItem::Range) - && let variant_field = - variant.fields.iter().find(|field| field.ident(self.tcx) == last_expr_field.ident) - && let range_def_id = self.tcx.lang_items().range_struct() - && variant_field - .and_then(|field| field.ty(self.tcx, args).skip_norm_wip().ty_adt_def()) - .map(|adt| adt.did()) - != range_def_id - { - // Use a (somewhat arbitrary) filtering heuristic to avoid printing - // expressions that are either too long, or have control character - // such as newlines in them. - let expr = self - .tcx - .sess - .source_map() - .span_to_snippet(range_end.expr.span) - .ok() - .filter(|s| s.len() < 25 && !s.contains(|c: char| c.is_control())); - - let fru_span = self - .tcx - .sess - .source_map() - .span_extend_while_whitespace(range_start.expr.span) - .shrink_to_hi() - .to(range_end.expr.span); - - err.subdiagnostic(TypeMismatchFruTypo { - expr_span: range_start.expr.span, - fru_span, - expr, - }); - - // Suppress any range expr type mismatches - self.dcx().try_steal_replace_and_emit_err( - last_expr_field.span, - StashKey::MaybeFruTypo, - err, - ); - } else { - err.emit(); - } - } - - /// Report an error for a struct field expression when there are invisible fields. - /// - /// ```text - /// error: cannot construct `Foo` with struct literal syntax due to private fields - /// --> src/main.rs:8:5 - /// | - /// 8 | foo::Foo {}; - /// | ^^^^^^^^ - /// - /// error: aborting due to 1 previous error - /// ``` - fn report_private_fields( - &self, - adt_ty: Ty<'tcx>, - span: Span, - expr_span: Span, - private_fields: Vec<&ty::FieldDef>, - used_fields: &'tcx [hir::ExprField<'tcx>], - ) { - let mut err = - self.dcx().struct_span_err( - span, - format!( - "cannot construct `{adt_ty}` with struct literal syntax due to private fields", - ), - ); - let (used_private_fields, remaining_private_fields): ( - Vec<(Symbol, Span, bool)>, - Vec<(Symbol, Span, bool)>, - ) = private_fields - .iter() - .map(|field| { - match used_fields.iter().find(|used_field| field.name == used_field.ident.name) { - Some(used_field) => (field.name, used_field.span, true), - None => (field.name, self.tcx.def_span(field.did), false), - } - }) - .partition(|field| field.2); - err.span_labels(used_private_fields.iter().map(|(_, span, _)| *span), "private field"); - - if let ty::Adt(def, _) = adt_ty.kind() { - if (def.did().is_local() || !used_fields.is_empty()) - && !remaining_private_fields.is_empty() - { - let names = if remaining_private_fields.len() > 6 { - String::new() - } else { - format!( - "{} ", - listify(&remaining_private_fields, |(name, _, _)| format!("`{name}`")) - .expect("expected at least one private field to report") - ) - }; - err.note(format!( - "{}private field{s} {names}that {were} not provided", - if used_fields.is_empty() { "" } else { "...and other " }, - s = pluralize!(remaining_private_fields.len()), - were = pluralize!("was", remaining_private_fields.len()), - )); - } - - let def_id = def.did(); - let mut items = self - .tcx - .inherent_impls(def_id) - .into_iter() - .flat_map(|&i| self.tcx.associated_items(i).in_definition_order()) - // Only assoc fn with no receivers. - .filter(|item| item.is_fn() && !item.is_method()) - .filter_map(|item| { - // Only assoc fns that return `Self` - let fn_sig = self - .tcx - .fn_sig(item.def_id) - .instantiate(self.tcx, self.fresh_args_for_item(span, item.def_id)) - .skip_norm_wip(); - let ret_ty = self.tcx.instantiate_bound_regions_with_erased(fn_sig.output()); - if !self.can_eq(self.param_env, ret_ty, adt_ty) { - return None; - } - let input_len = fn_sig.inputs().skip_binder().len(); - let name = item.name(); - let order = !name.as_str().starts_with("new"); - Some((order, name, input_len)) - }) - .collect::>(); - items.sort_by_key(|(order, _, _)| *order); - let suggestion = |name, args| { - format!( - "::{name}({})", - std::iter::repeat_n("_", args).collect::>().join(", ") - ) - }; - match &items[..] { - [] => {} - [(_, name, args)] => { - err.span_suggestion_verbose( - span.shrink_to_hi().with_hi(expr_span.hi()), - format!("you might have meant to use the `{name}` associated function"), - suggestion(name, *args), - Applicability::MaybeIncorrect, - ); - } - _ => { - err.span_suggestions( - span.shrink_to_hi().with_hi(expr_span.hi()), - "you might have meant to use an associated function to build this type", - items.iter().map(|(_, name, args)| suggestion(name, *args)), - Applicability::MaybeIncorrect, - ); - } - } - if let Some(default_trait) = self.tcx.get_diagnostic_item(sym::Default) - && self - .infcx - .type_implements_trait(default_trait, [adt_ty], self.param_env) - .may_apply() - { - err.multipart_suggestion( - "consider using the `Default` trait", - vec![ - (span.shrink_to_lo(), "<".to_string()), - ( - span.shrink_to_hi().with_hi(expr_span.hi()), - " as std::default::Default>::default()".to_string(), - ), - ], - Applicability::MaybeIncorrect, - ); - } - } - - err.emit(); - } - - fn report_unknown_field( - &self, - ty: Ty<'tcx>, - variant: &'tcx ty::VariantDef, - expr: &hir::Expr<'_>, - field: &hir::ExprField<'_>, - skip_fields: &[hir::ExprField<'_>], - kind_name: &str, - ) -> ErrorGuaranteed { - // we don't care to report errors for a struct if the struct itself is tainted - if let Err(guar) = variant.has_errors() { - return guar; - } - let mut err = self.err_ctxt().type_error_struct_with_diag( - field.ident.span, - |actual| match ty.kind() { - ty::Adt(adt, ..) if adt.is_enum() => struct_span_code_err!( - self.dcx(), - field.ident.span, - E0559, - "{} `{}::{}` has no field named `{}`", - kind_name, - actual, - variant.name, - field.ident - ), - _ => struct_span_code_err!( - self.dcx(), - field.ident.span, - E0560, - "{} `{}` has no field named `{}`", - kind_name, - actual, - field.ident - ), - }, - ty, - ); - - let variant_ident_span = self.tcx.def_ident_span(variant.def_id).unwrap(); - match variant.ctor { - Some((CtorKind::Fn, def_id)) => match ty.kind() { - ty::Adt(adt, ..) if adt.is_enum() => { - err.span_context(self.tcx.def_span(adt.did()).shrink_to_lo()); - err.span_label( - variant_ident_span, - format!( - "`{adt}::{variant}` defined here", - adt = ty, - variant = variant.name, - ), - ); - err.span_label(field.ident.span, "field does not exist"); - let fn_sig = self.tcx.fn_sig(def_id).instantiate_identity().skip_norm_wip(); - let inputs = fn_sig.inputs().skip_binder(); - let fields = format!( - "({})", - inputs.iter().map(|i| format!("/* {i} */")).collect::>().join(", ") - ); - let (replace_span, sugg) = match expr.kind { - hir::ExprKind::Struct(qpath, ..) => { - (qpath.span().shrink_to_hi().with_hi(expr.span.hi()), fields) - } - _ => { - (expr.span, format!("{ty}::{variant}{fields}", variant = variant.name)) - } - }; - err.span_suggestion_verbose( - replace_span, - format!( - "`{adt}::{variant}` is a tuple {kind_name}, use the appropriate syntax", - adt = ty, - variant = variant.name, - ), - sugg, - Applicability::HasPlaceholders, - ); - } - _ => { - err.span_label(variant_ident_span, format!("`{ty}` defined here")); - err.span_label(field.ident.span, "field does not exist"); - let fn_sig = self.tcx.fn_sig(def_id).instantiate_identity().skip_norm_wip(); - let inputs = fn_sig.inputs().skip_binder(); - let fields = format!( - "({})", - inputs.iter().map(|i| format!("/* {i} */")).collect::>().join(", ") - ); - err.span_suggestion_verbose( - expr.span, - format!("`{ty}` is a tuple {kind_name}, use the appropriate syntax",), - format!("{ty}{fields}"), - Applicability::HasPlaceholders, - ); - } - }, - _ => { - // prevent all specified fields from being suggested - let available_field_names = self.available_field_names(variant, expr, skip_fields); - if let Some(field_name) = - find_best_match_for_name(&available_field_names, field.ident.name, None) - && !(field.ident.name.as_str().parse::().is_ok() - && field_name.as_str().parse::().is_ok()) - { - err.span_label(field.ident.span, "unknown field"); - err.span_suggestion_verbose( - field.ident.span, - "a field with a similar name exists", - field_name, - Applicability::MaybeIncorrect, - ); - } else { - match ty.kind() { - ty::Adt(adt, ..) => { - if adt.is_enum() { - err.span_label( - field.ident.span, - format!("`{}::{}` does not have this field", ty, variant.name), - ); - } else { - err.span_label( - field.ident.span, - format!("`{ty}` does not have this field"), - ); - } - if available_field_names.is_empty() { - err.note("all struct fields are already assigned"); - } else { - err.note(format!( - "available fields are: {}", - self.name_series_display(available_field_names) - )); - } - } - _ => bug!("non-ADT passed to report_unknown_field"), - } - }; - } - } - err.emit_err() - } - - fn available_field_names( + pub(crate) fn available_field_names( &self, variant: &'tcx ty::VariantDef, expr: &hir::Expr<'_>, @@ -2774,17 +2275,6 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { .collect() } - fn name_series_display(&self, names: Vec) -> String { - // dynamic limit, to never omit just one field - let limit = if names.len() == 6 { 6 } else { 5 }; - let mut display = - names.iter().take(limit).map(|n| format!("`{n}`")).collect::>().join(", "); - if names.len() > limit { - display = format!("{} ... and {} others", display, names.len() - limit); - } - display - } - /// Find the position of a field named `ident` in `base_def`, accounting for unnammed fields. /// Return whether such a field has been found. The path to it is stored in `nested_fields`. /// `ident` must have been adjusted beforehand. @@ -2990,517 +2480,6 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { Ty::new_error(self.tcx(), guar) } - fn suggest_await_on_field_access( - &self, - err: &mut Diag<'_>, - field_ident: Ident, - base: &'tcx hir::Expr<'tcx>, - ty: Ty<'tcx>, - ) { - let Some(output_ty) = self.tcx.get_impl_future_output_ty(ty) else { - err.span_label(field_ident.span, "unknown field"); - return; - }; - let ty::Adt(def, _) = output_ty.kind() else { - err.span_label(field_ident.span, "unknown field"); - return; - }; - // no field access on enum type - if def.is_enum() { - err.span_label(field_ident.span, "unknown field"); - return; - } - if !def.non_enum_variant().fields.iter().any(|field| field.ident(self.tcx) == field_ident) { - err.span_label(field_ident.span, "unknown field"); - return; - } - err.span_label( - field_ident.span, - "field not available in `impl Future`, but it is available in its `Output`", - ); - match self.tcx.coroutine_kind(self.body_def_id) { - Some(hir::CoroutineKind::Desugared(hir::CoroutineDesugaring::Async, _)) => { - err.span_suggestion_verbose( - base.span.shrink_to_hi(), - "consider `await`ing on the `Future` to access the field", - ".await", - Applicability::MaybeIncorrect, - ); - } - _ => { - let mut span: MultiSpan = base.span.into(); - span.push_span_label(self.tcx.def_span(self.body_def_id), "this is not `async`"); - err.span_note( - span, - "this implements `Future` and its output type has the field, \ - but the future cannot be awaited in a synchronous function", - ); - } - } - } - - fn ban_nonexisting_field( - &self, - ident: Ident, - base: &'tcx hir::Expr<'tcx>, - expr: &'tcx hir::Expr<'tcx>, - base_ty: Ty<'tcx>, - ) -> ErrorGuaranteed { - debug!( - "ban_nonexisting_field: field={:?}, base={:?}, expr={:?}, base_ty={:?}", - ident, base, expr, base_ty - ); - let mut err = self.no_such_field_err(ident, base_ty, expr); - - match *base_ty.peel_refs().kind() { - ty::Array(_, len) => { - self.maybe_suggest_array_indexing(&mut err, base, ident, len); - } - ty::RawPtr(..) => { - self.suggest_first_deref_field(&mut err, base, ident); - } - ty::Param(param_ty) => { - err.span_label(ident.span, "unknown field"); - self.point_at_param_definition(&mut err, param_ty); - } - ty::Alias(_, ty::AliasTy { kind: ty::Opaque { .. }, .. }) => { - self.suggest_await_on_field_access(&mut err, ident, base, base_ty.peel_refs()); - } - _ => { - err.span_label(ident.span, "unknown field"); - } - } - - self.suggest_fn_call(&mut err, base, base_ty, |output_ty| { - if let ty::Adt(def, _) = output_ty.kind() - && !def.is_enum() - { - def.non_enum_variant().fields.iter().any(|field| { - field.ident(self.tcx) == ident - && field.vis.is_accessible_from(expr.hir_id.owner.def_id, self.tcx) - }) - } else if let ty::Tuple(tys) = output_ty.kind() - && let Ok(idx) = ident.as_str().parse::() - { - idx < tys.len() - } else { - false - } - }); - - if ident.name == kw::Await { - // We know by construction that `.await` is either on Rust 2015 - // or results in `ExprKind::Await`. Suggest switching the edition to 2018. - err.note("to `.await` a `Future`, switch to Rust 2018 or later"); - HelpUseLatestEdition::new().add_to_diag(&mut err); - } - - err.emit_err() - } - - fn ban_private_field_access( - &self, - expr: &hir::Expr<'tcx>, - expr_t: Ty<'tcx>, - field: Ident, - base_did: DefId, - return_ty: Option>, - ) -> ErrorGuaranteed { - let mut err = self.private_field_err(field, base_did); - - // Also check if an accessible method exists, which is often what is meant. - if self.method_exists_for_diagnostic(field, expr_t, expr.hir_id, return_ty) - && !self.expr_in_place(expr.hir_id) - { - self.suggest_method_call( - &mut err, - format!("a method `{field}` also exists, call it with parentheses"), - field, - expr_t, - expr, - None, - ); - } - err.emit_err() - } - - fn ban_take_value_of_method( - &self, - expr: &hir::Expr<'tcx>, - expr_t: Ty<'tcx>, - field: Ident, - ) -> ErrorGuaranteed { - let mut err = type_error_struct!( - self.dcx(), - field.span, - expr_t, - E0615, - "attempted to take value of method `{field}` on type `{expr_t}`", - ); - err.span_label(field.span, "method, not a field"); - let expr_is_call = - if let hir::Node::Expr(hir::Expr { kind: ExprKind::Call(callee, _args), .. }) = - self.tcx.parent_hir_node(expr.hir_id) - { - expr.hir_id == callee.hir_id - } else { - false - }; - let expr_snippet = - self.tcx.sess.source_map().span_to_snippet(expr.span).unwrap_or_default(); - let is_wrapped = expr_snippet.starts_with('(') && expr_snippet.ends_with(')'); - let after_open = expr.span.lo() + rustc_span::BytePos(1); - let before_close = expr.span.hi() - rustc_span::BytePos(1); - - if expr_is_call && is_wrapped { - err.multipart_suggestion( - "remove wrapping parentheses to call the method", - vec![ - (expr.span.with_hi(after_open), String::new()), - (expr.span.with_lo(before_close), String::new()), - ], - Applicability::MachineApplicable, - ); - } else if !self.expr_in_place(expr.hir_id) { - // Suggest call parentheses inside the wrapping parentheses - let span = if is_wrapped { - expr.span.with_lo(after_open).with_hi(before_close) - } else { - expr.span - }; - self.suggest_method_call( - &mut err, - "use parentheses to call the method", - field, - expr_t, - expr, - Some(span), - ); - } else if let ty::RawPtr(ptr_ty, _) = expr_t.kind() - && let ty::Adt(adt_def, _) = ptr_ty.kind() - && let ExprKind::Field(base_expr, _) = expr.kind - && let [variant] = &adt_def.variants().raw - && variant.fields.iter().any(|f| f.ident(self.tcx) == field) - { - err.multipart_suggestion( - "to access the field, dereference first", - vec![ - (base_expr.span.shrink_to_lo(), "(*".to_string()), - (base_expr.span.shrink_to_hi(), ")".to_string()), - ], - Applicability::MaybeIncorrect, - ); - } else { - err.help("methods are immutable and cannot be assigned to"); - } - - // See `StashKey::GenericInFieldExpr` for more info - self.dcx().try_steal_replace_and_emit_err(field.span, StashKey::GenericInFieldExpr, err) - } - - fn point_at_param_definition(&self, err: &mut Diag<'_>, param: ty::ParamTy) { - let generics = self.tcx.generics_of(self.body_def_id); - let generic_param = generics.type_param(param, self.tcx); - if let ty::GenericParamDefKind::Type { synthetic: true, .. } = generic_param.kind { - return; - } - let param_def_id = generic_param.def_id; - let param_hir_id = match param_def_id.as_local() { - Some(x) => self.tcx.local_def_id_to_hir_id(x), - None => return, - }; - let param_span = self.tcx.hir_span(param_hir_id); - let param_name = self.tcx.hir_ty_param_name(param_def_id.expect_local()); - - err.span_label(param_span, format!("type parameter '{param_name}' declared here")); - } - - fn maybe_suggest_array_indexing( - &self, - err: &mut Diag<'_>, - base: &hir::Expr<'_>, - field: Ident, - len: ty::Const<'tcx>, - ) { - err.span_label(field.span, "unknown field"); - if let (Some(len), Ok(user_index)) = ( - self.try_structurally_resolve_const(base.span, len).try_to_target_usize(self.tcx), - field.as_str().parse::(), - ) { - let help = "instead of using tuple indexing, use array indexing"; - let applicability = if len < user_index { - Applicability::MachineApplicable - } else { - Applicability::MaybeIncorrect - }; - err.multipart_suggestion( - help, - vec![ - (base.span.between(field.span), "[".to_string()), - (field.span.shrink_to_hi(), "]".to_string()), - ], - applicability, - ); - } - } - - fn suggest_first_deref_field(&self, err: &mut Diag<'_>, base: &hir::Expr<'_>, field: Ident) { - err.span_label(field.span, "unknown field"); - if base.span.from_expansion() || field.span.from_expansion() { - return; - } - let val = if let Ok(base) = self.tcx.sess.source_map().span_to_snippet(base.span) - && base.len() < 20 - { - format!("`{base}`") - } else { - "the value".to_string() - }; - err.multipart_suggestion( - format!("{val} is a raw pointer; try dereferencing it"), - vec![ - (base.span.shrink_to_lo(), "(*".into()), - (base.span.between(field.span), format!(").")), - ], - Applicability::MaybeIncorrect, - ); - } - - fn no_such_field_err( - &self, - field: Ident, - base_ty: Ty<'tcx>, - expr: &hir::Expr<'tcx>, - ) -> Diag<'_> { - let span = field.span; - debug!("no_such_field_err(span: {:?}, field: {:?}, expr_t: {:?})", span, field, base_ty); - - let mut err = self.dcx().create_err(NoFieldOnType { span, ty: base_ty, field }); - if base_ty.references_error() { - err.downgrade_to_delayed_bug(); - } - - if let Some(within_macro_span) = span.within_macro(expr.span, self.tcx.sess.source_map()) { - err.span_label(within_macro_span, "due to this macro variable"); - } - - // Check if there is an associated function with the same name. - if let Some(def_id) = base_ty.peel_refs().ty_adt_def().map(|d| d.did()) { - for &impl_def_id in self.tcx.inherent_impls(def_id) { - for item in self.tcx.associated_items(impl_def_id).in_definition_order() { - if let ExprKind::Field(base_expr, _) = expr.kind - && item.name() == field.name - && matches!(item.kind, ty::AssocKind::Fn { has_self: false, .. }) - { - err.span_label(field.span, "this is an associated function, not a method"); - err.note("found the following associated function; to be used as method, it must have a `self` parameter"); - let impl_ty = - self.tcx.type_of(impl_def_id).instantiate_identity().skip_norm_wip(); - err.span_note( - self.tcx.def_span(item.def_id), - format!("the candidate is defined in an impl for the type `{impl_ty}`"), - ); - - let ty_str = match base_ty.peel_refs().kind() { - ty::Adt(def, args) => self.tcx.def_path_str_with_args(def.did(), *args), - _ => base_ty.peel_refs().to_string(), - }; - err.multipart_suggestion( - "use associated function syntax instead", - vec![ - (base_expr.span, ty_str), - (base_expr.span.between(field.span), "::".to_string()), - ], - Applicability::MaybeIncorrect, - ); - return err; - } - } - } - } - - // try to add a suggestion in case the field is a nested field of a field of the Adt - let (ty, unwrap) = if let ty::Adt(def, args) = base_ty.kind() - && (self.tcx.is_diagnostic_item(sym::Result, def.did()) - || self.tcx.is_diagnostic_item(sym::Option, def.did())) - && let Some(arg) = args.get(0) - && let Some(ty) = arg.as_type() - { - (ty, "unwrap().") - } else { - (base_ty, "") - }; - for found_fields in self.get_field_candidates_considering_privacy_for_diag(span, ty) { - let field_names = found_fields.iter().map(|field| field.0.name).collect::>(); - let mut candidate_fields: Vec<_> = found_fields - .into_iter() - .filter_map(|candidate_field| { - self.check_for_nested_field_satisfying_condition_for_diag( - span, - &|candidate_field, _| candidate_field == field, - candidate_field, - vec![], - ) - }) - .map(|mut field_path| { - field_path.pop(); - field_path.iter().map(|id| format!("{}.", id)).collect::() - }) - .collect::>(); - candidate_fields.sort(); - - let len = candidate_fields.len(); - // Don't suggest `.field` if the base expr is from a different - // syntax context than the field. - if len > 0 && expr.span.ctxt() == field.span.ctxt() { - err.span_suggestions( - field.span.shrink_to_lo(), - format!( - "{} of the expressions' fields {} a field of the same name", - if len > 1 { "some" } else { "one" }, - if len > 1 { "have" } else { "has" }, - ), - candidate_fields.iter().map(|path| format!("{unwrap}{path}")), - Applicability::MaybeIncorrect, - ); - } else if let Some(field_name) = - find_best_match_for_name(&field_names, field.name, None) - && !(field.name.as_str().parse::().is_ok() - && field_name.as_str().parse::().is_ok()) - { - err.span_suggestion_verbose( - field.span, - "a field with a similar name exists", - format!("{unwrap}{}", field_name), - Applicability::MaybeIncorrect, - ); - } else if !field_names.is_empty() { - let is = if field_names.len() == 1 { " is" } else { "s are" }; - err.note( - format!("available field{is}: {}", self.name_series_display(field_names),), - ); - } - } - err - } - - fn private_field_err(&self, field: Ident, base_did: DefId) -> Diag<'_> { - let struct_path = self.tcx().def_path_str(base_did); - let kind_name = self.tcx().def_descr(base_did); - struct_span_code_err!( - self.dcx(), - field.span, - E0616, - "field `{field}` of {kind_name} `{struct_path}` is private", - ) - .with_span_label(field.span, "private field") - } - - pub(crate) fn get_field_candidates_considering_privacy_for_diag( - &self, - span: Span, - base_ty: Ty<'tcx>, - ) -> Vec)>> { - debug!("get_field_candidates(span: {:?}, base_t: {:?}", span, base_ty); - - let mut autoderef = self.autoderef(span, base_ty).silence_errors(); - let deref_chain: Vec<_> = autoderef.by_ref().collect(); - - // Don't probe if we hit the recursion limit, since it may result in - // quadratic blowup if we then try to further deref the results of this - // function. This is a best-effort method, after all. - if autoderef.reached_recursion_limit() { - return vec![]; - } - - deref_chain - .into_iter() - .filter_map(move |(base_t, _)| { - match base_t.kind() { - ty::Adt(base_def, args) if !base_def.is_enum() => { - let tcx = self.tcx; - let fields = &base_def.non_enum_variant().fields; - // Some struct, e.g. some that impl `Deref`, have all private fields - // because you're expected to deref them to access the _real_ fields. - // This, for example, will help us suggest accessing a field through a `Box`. - if fields - .iter() - .all(|field| !field.vis.is_accessible_from(self.mod_id, tcx)) - { - return None; - } - return Some( - fields - .iter() - .filter(move |field| { - field.vis.is_accessible_from(self.mod_id, tcx) - && self.is_field_suggestable(field, span) - }) - // For compile-time reasons put a limit on number of fields we search - .take(100) - .map(|field_def| { - ( - field_def.ident(self.tcx).normalize_to_macros_2_0(), - field_def.ty(self.tcx, *args).skip_norm_wip(), - ) - }) - .collect::>(), - ); - } - ty::Tuple(types) => { - return Some( - types - .iter() - .enumerate() - // For compile-time reasons put a limit on number of fields we search - .take(100) - .map(|(i, ty)| (Ident::from_str(&i.to_string()), ty)) - .collect::>(), - ); - } - _ => None, - } - }) - .collect() - } - - /// This method is called after we have encountered a missing field error to recursively - /// search for the field - #[instrument(skip(self, matches), level = "debug")] - pub(crate) fn check_for_nested_field_satisfying_condition_for_diag( - &self, - span: Span, - matches: &impl Fn(Ident, Ty<'tcx>) -> bool, - (candidate_name, candidate_ty): (Ident, Ty<'tcx>), - mut field_path: Vec, - ) -> Option> { - if field_path.len() > 3 { - // For compile-time reasons and to avoid infinite recursion we only check for fields - // up to a depth of three - return None; - } - field_path.push(candidate_name); - if matches(candidate_name, candidate_ty) { - return Some(field_path); - } - for nested_fields in - self.get_field_candidates_considering_privacy_for_diag(span, candidate_ty) - { - // recursively search fields of `candidate_field` if it's a ty::Adt - for field in nested_fields { - if let Some(field_path) = self.check_for_nested_field_satisfying_condition_for_diag( - span, - matches, - field, - field_path.clone(), - ) { - return Some(field_path); - } - } - } - None - } - fn check_expr_index( &self, base: &'tcx hir::Expr<'tcx>, @@ -3687,34 +2666,6 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { .ok() } - fn point_at_index(&self, errors: &mut ThinVec>, span: Span) { - let mut seen_preds = FxHashSet::default(); - // We re-sort here so that the outer most root obligations comes first, as we have the - // subsequent weird logic to identify *every* relevant obligation for proper deduplication - // of diagnostics. - errors.sort_by_key(|error| error.root_obligation.recursion_depth); - for error in errors { - match ( - error.root_obligation.predicate.kind().skip_binder(), - error.obligation.predicate.kind().skip_binder(), - ) { - (ty::PredicateKind::Clause(ty::ClauseKind::Trait(predicate)), _) - if self.tcx.is_lang_item(predicate.trait_ref.def_id, LangItem::Index) => - { - seen_preds.insert(error.obligation.predicate.kind().skip_binder()); - } - (_, ty::PredicateKind::Clause(ty::ClauseKind::Trait(predicate))) - if self.tcx.is_diagnostic_item(sym::SliceIndex, predicate.trait_ref.def_id) => - { - seen_preds.insert(error.obligation.predicate.kind().skip_binder()); - } - (root, pred) if seen_preds.contains(&pred) || seen_preds.contains(&root) => {} - _ => continue, - } - error.obligation.cause.span = span; - } - } - fn check_expr_yield( &self, value: &'tcx hir::Expr<'tcx>, diff --git a/compiler/rustc_hir_typeck/src/fn_ctxt/checks.rs b/compiler/rustc_hir_typeck/src/fn_ctxt/checks.rs index 91afc6369d62b..5d116feb06cb9 100644 --- a/compiler/rustc_hir_typeck/src/fn_ctxt/checks.rs +++ b/compiler/rustc_hir_typeck/src/fn_ctxt/checks.rs @@ -3479,7 +3479,7 @@ impl<'a, 'tcx> ArgsCtxt<'a, 'tcx> { callee_ty.peel_refs(), self.call_ctxt.callee_expr.unwrap().hir_id, TraitsInScope, - |mut ctxt| ctxt.probe_for_similar_candidate(), + |mut ctxt| ctxt.probe_for_similar_candidate(&[]), ) && assoc.is_method() { diff --git a/compiler/rustc_hir_typeck/src/lib.rs b/compiler/rustc_hir_typeck/src/lib.rs index 150a8b5b8f41b..618052418c3f9 100644 --- a/compiler/rustc_hir_typeck/src/lib.rs +++ b/compiler/rustc_hir_typeck/src/lib.rs @@ -17,6 +17,7 @@ mod coercion; mod demand; mod diagnostics; mod diverges; +mod errors; mod expectation; mod expr; mod inline_asm; diff --git a/compiler/rustc_hir_typeck/src/method/probe.rs b/compiler/rustc_hir_typeck/src/method/probe.rs index bdad342b52de5..4e05903660f02 100644 --- a/compiler/rustc_hir_typeck/src/method/probe.rs +++ b/compiler/rustc_hir_typeck/src/method/probe.rs @@ -1305,7 +1305,7 @@ impl<'a, 'tcx> ProbeContext<'a, 'tcx> { if let Some((kind, def_id)) = private_candidate { return Err(MethodError::PrivateMatch(kind, def_id, out_of_scope_traits)); } - let similar_candidate = self.probe_for_similar_candidate()?; + let similar_candidate = self.probe_for_similar_candidate(&out_of_scope_traits)?; Err(MethodError::NoMatch(NoMatchData { static_candidates, @@ -2519,6 +2519,7 @@ impl<'a, 'tcx> ProbeContext<'a, 'tcx> { #[instrument(level = "debug", skip(self))] pub(crate) fn probe_for_similar_candidate( &mut self, + out_of_scope_traits: &[DefId], ) -> Result, MethodError<'tcx>> { debug!("probing for method names similar to {:?}", self.method_name); @@ -2547,6 +2548,11 @@ impl<'a, 'tcx> ProbeContext<'a, 'tcx> { pcx.method_name = Some(method_name); pcx.assemble_inherent_candidates(); pcx.assemble_extension_candidates_for_all_traits(); + // Methods of out-of-scope traits can't be called here. Drop them before + // picking, or they could win over (or be ambiguous with) one that can. + pcx.extension_candidates.retain(|candidate| { + !out_of_scope_traits.contains(&candidate.item.container_id(self.tcx)) + }); pcx.pick_core(&mut Vec::new()).and_then(|pick| pick.ok()).map(|pick| pick.item) }) .collect(); diff --git a/compiler/rustc_hir_typeck/src/method/suggest.rs b/compiler/rustc_hir_typeck/src/method/suggest.rs index d4487bfaea67c..20eb43ba718e6 100644 --- a/compiler/rustc_hir_typeck/src/method/suggest.rs +++ b/compiler/rustc_hir_typeck/src/method/suggest.rs @@ -583,10 +583,27 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { Applicability::MachineApplicable, ); } - + self.detect_shadowed_method_on_incorrect_method_access( + &mut err, source, item_ident, rcvr_ty, + ); err } + fn detect_shadowed_method_on_incorrect_method_access( + &self, + err: &mut Diag<'_>, + source: SelfSource<'tcx>, + method_ident: Ident, + base_ty: Ty<'tcx>, + ) { + let SelfSource::MethodCall(expr) = source else { return }; + self.find_shadowed_method_and_provide_diagnostic_context(err, base_ty, expr, |ty| { + self.autoderef(method_ident.span, ty) + .silence_errors() + .any(|(ty, _)| self.all_methods(method_ident, ty).next().is_some()) + }); + } + fn suggest_use_shadowed_binding_with_method( &self, self_source: SelfSource<'tcx>, diff --git a/compiler/rustc_hir_typeck/src/op.rs b/compiler/rustc_hir_typeck/src/op.rs index 526f29cb3753b..af46f98d704aa 100644 --- a/compiler/rustc_hir_typeck/src/op.rs +++ b/compiler/rustc_hir_typeck/src/op.rs @@ -343,6 +343,20 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { let lhs_ty_str = self.tcx.short_string(lhs_ty, &mut path); let rhs_ty_str = self.tcx.short_string(rhs_ty, &mut path); + let is_compatible_after_call = |lhs_ty, rhs_ty| { + let op_ok = self + .lookup_op_method( + (lhs_expr, lhs_ty), + Some((rhs_expr, rhs_ty)), + lang_item_for_binop(self.tcx, op), + op.span(), + expected, + ) + .is_ok(); + + op_ok || self.can_eq(self.param_env, lhs_ty, rhs_ty) + }; + let (mut err, output_def_id) = match op { // Try and detect when `+=` was incorrectly // used instead of `==` in a let-chain @@ -439,6 +453,20 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { ); let suggest_derive = self.can_eq(self.param_env, lhs_ty, rhs_ty); self.note_unmet_impls_on_type(&mut err, &errors, suggest_derive); + + // The other case, where RHS had a shadowed method call earlier in the chain + // produces an E0277 instead, so adding a second call to + // `find_shadowed_method_and_provide_diagnostic_context` would be dead code. + self.find_shadowed_method_and_provide_diagnostic_context( + &mut err, + lhs_ty, + lhs_expr, + |ty| { + self.autoderef(lhs_expr.span, ty) + .silence_errors() + .any(|(ty, _)| is_compatible_after_call(ty, rhs_ty)) + }, + ); (err, output_def_id) } }; @@ -454,20 +482,6 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { err.downgrade_to_delayed_bug(); } - let is_compatible_after_call = |lhs_ty, rhs_ty| { - let op_ok = self - .lookup_op_method( - (lhs_expr, lhs_ty), - Some((rhs_expr, rhs_ty)), - lang_item_for_binop(self.tcx, op), - op.span(), - expected, - ) - .is_ok(); - - op_ok || self.can_eq(self.param_env, lhs_ty, rhs_ty) - }; - // We should suggest `a + b` => `*a + b` if `a` is copy, and suggest // `a += b` => `*a += b` if a is a mut ref. self.suggest_deref_or_call_for_binop_error( diff --git a/compiler/rustc_lint/src/context.rs b/compiler/rustc_lint/src/context.rs index 9423bec5a8715..da0c8a195cf1a 100644 --- a/compiler/rustc_lint/src/context.rs +++ b/compiler/rustc_lint/src/context.rs @@ -352,7 +352,7 @@ impl LintStore { // FIXME: rustc and rustdoc are considered tools for lints, but not for attributes. if tool_name != sym::rustc && tool_name != sym::rustdoc - && !registered_lint_tools.contains(&Ident::with_dummy_span(tool_name)) + && !registered_lint_tools.contains_key(&Ident::with_dummy_span(tool_name)) { return CheckLintNameResult::NoTool(tool_name); } diff --git a/compiler/rustc_lint/src/disallowed_pass_by_ref.rs b/compiler/rustc_lint/src/disallowed_pass_by_ref.rs index a373436d4298f..5939a1da7876a 100644 --- a/compiler/rustc_lint/src/disallowed_pass_by_ref.rs +++ b/compiler/rustc_lint/src/disallowed_pass_by_ref.rs @@ -15,7 +15,7 @@ declare_tool_lint! { pub rustc::DISALLOWED_PASS_BY_REF, Warn, "pass by reference of a type flagged as `#[rustc_pass_by_value]`", - report_in_external_macro: true + @report_in_external_macro = true } declare_lint_pass!(DisallowedPassByRef => [DISALLOWED_PASS_BY_REF]); diff --git a/compiler/rustc_lint/src/internal.rs b/compiler/rustc_lint/src/internal.rs index 296e5dbc5ff83..9a425c6167182 100644 --- a/compiler/rustc_lint/src/internal.rs +++ b/compiler/rustc_lint/src/internal.rs @@ -34,7 +34,7 @@ declare_tool_lint! { pub rustc::DEFAULT_HASH_TYPES, Allow, "forbid HashMap and HashSet and suggest the FxHash* variants", - report_in_external_macro: true + @report_in_external_macro = true } declare_lint_pass!(DefaultHashTypes => [DEFAULT_HASH_TYPES]); @@ -73,7 +73,7 @@ declare_tool_lint! { pub rustc::POTENTIAL_QUERY_INSTABILITY, Allow, "require explicit opt-in when using potentially unstable methods or functions", - report_in_external_macro: true + @report_in_external_macro = true } declare_tool_lint! { @@ -84,7 +84,7 @@ declare_tool_lint! { pub rustc::UNTRACKED_QUERY_INFORMATION, Allow, "require explicit opt-in when accessing information not tracked by the query system", - report_in_external_macro: true + @report_in_external_macro = true } declare_lint_pass!(QueryStability => [POTENTIAL_QUERY_INSTABILITY, UNTRACKED_QUERY_INFORMATION]); @@ -201,7 +201,7 @@ declare_tool_lint! { pub rustc::USAGE_OF_TY_TYKIND, Allow, "usage of `ty::TyKind` outside of the `ty::sty` module", - report_in_external_macro: true + @report_in_external_macro = true } declare_tool_lint! { @@ -210,7 +210,7 @@ declare_tool_lint! { pub rustc::USAGE_OF_QUALIFIED_TY, Allow, "using `ty::{Ty,TyCtxt}` instead of importing it", - report_in_external_macro: true + @report_in_external_macro = true } declare_lint_pass!(TyTyKind => [ @@ -347,7 +347,7 @@ declare_tool_lint! { pub rustc::NON_GLOB_IMPORT_OF_TYPE_IR_INHERENT, Allow, "non-glob import of `rustc_type_ir::inherent`", - report_in_external_macro: true + @report_in_external_macro = true } declare_tool_lint! { @@ -357,7 +357,7 @@ declare_tool_lint! { pub rustc::USAGE_OF_TYPE_IR_INHERENT, Allow, "usage `rustc_type_ir::inherent` outside of trait system", - report_in_external_macro: true + @report_in_external_macro = true } declare_tool_lint! { @@ -370,7 +370,7 @@ declare_tool_lint! { pub rustc::USAGE_OF_TYPE_IR_TRAITS, Allow, "usage `rustc_type_ir`-specific abstraction traits outside of trait system", - report_in_external_macro: true + @report_in_external_macro = true } declare_tool_lint! { /// The `direct_use_of_rustc_type_ir` lint detects usage of `rustc_type_ir`. @@ -380,7 +380,7 @@ declare_tool_lint! { pub rustc::DIRECT_USE_OF_RUSTC_TYPE_IR, Allow, "usage `rustc_type_ir` abstraction outside of trait system", - report_in_external_macro: true + @report_in_external_macro = true } declare_lint_pass!(TypeIr => [ @@ -541,7 +541,7 @@ declare_tool_lint! { pub rustc::BAD_OPT_ACCESS, Deny, "prevent using options by field access when there is a wrapper function", - report_in_external_macro: true + @report_in_external_macro = true } declare_lint_pass!(BadOptAccess => [BAD_OPT_ACCESS]); @@ -575,7 +575,7 @@ declare_tool_lint! { pub rustc::SYMBOL_INTERN_STRING_LITERAL, Allow, "Forbid uses of string literals in `Symbol::intern` or `Ident::from_str_and_span`, suggesting preinterning instead", - report_in_external_macro: true + @report_in_external_macro = true } declare_lint_pass!(SymbolInternStringLiteral => [SYMBOL_INTERN_STRING_LITERAL]); @@ -617,7 +617,7 @@ declare_tool_lint! { pub rustc::IMPLICIT_SYSROOT_CRATE_IMPORT, Allow, "Forbid uses of non-sysroot crates in `extern crate`", - report_in_external_macro: true + @report_in_external_macro = true } declare_lint_pass!(ImplicitSysrootCrateImport => [IMPLICIT_SYSROOT_CRATE_IMPORT]); @@ -651,7 +651,7 @@ declare_tool_lint! { pub rustc::BAD_USE_OF_FIND_ATTR, Allow, "Forbid `AttributeKind::` as a prefix in `find_attr!` macros.", - report_in_external_macro: true + @report_in_external_macro = true } declare_lint_pass!(BadUseOfFindAttr => [BAD_USE_OF_FIND_ATTR]); @@ -739,7 +739,7 @@ declare_tool_lint! { pub rustc::RUSTC_MUST_MATCH_EXHAUSTIVELY, Allow, "Forbids matches with wildcards, or if-let matching on enums marked with `#[rustc_must_match_exhaustively]`", - report_in_external_macro: true + @report_in_external_macro = true } declare_lint_pass!(RustcMustMatchExhaustively => [RUSTC_MUST_MATCH_EXHAUSTIVELY]); @@ -853,7 +853,7 @@ declare_tool_lint! { // This lint is meant to be manually enabled in selected crates (currently only `rustc_type_ir`) Allow, "Forbid implementing `TypeVisitable` without deriving `GenericTypeVisitable`", - report_in_external_macro: true + @report_in_external_macro = true } declare_lint_pass!(MissingGenericTypeVisitableDerive => [MISSING_GENERIC_TYPE_VISITABLE_DERIVE]); diff --git a/compiler/rustc_lint_defs/src/lib.rs b/compiler/rustc_lint_defs/src/lib.rs index 956975536c424..019bb098e99a2 100644 --- a/compiler/rustc_lint_defs/src/lib.rs +++ b/compiler/rustc_lint_defs/src/lib.rs @@ -8,7 +8,7 @@ use std::borrow::Cow; use std::fmt::Display; use rustc_ast::attr::version::RustcVersion; -use rustc_data_structures::fx::FxIndexSet; +use rustc_data_structures::fx::FxIndexMap; use rustc_data_structures::stable_hash::{StableCompare, StableHash, StableHashCtxt, StableHasher}; use rustc_error_messages::{DiagArgValue, IntoDiagArg}; use rustc_hir_id::HirId; @@ -18,6 +18,7 @@ use rustc_span::{AttrId, Ident, Symbol, sym}; use serde::{Deserialize, Serialize}; pub use self::Level::*; +use crate::Reflectiveness::{NonReflective, Reflective}; pub mod builtin; @@ -603,7 +604,36 @@ pub enum DeprecatedSinceKind { InVersion(String), } -pub type RegisteredTools = FxIndexSet; +/// Tool attributes from this tool can be queried using reflection +#[derive(Encodable, Decodable, Copy, Clone, Debug, PartialEq, Eq, Hash)] +#[derive(StableHash)] +pub enum Reflectiveness { + NonReflective, + Reflective, +} + +/// Configured options for a registered tool +#[derive(Encodable, Decodable, Copy, Clone, Debug, PartialEq, Eq, Hash)] +#[derive(StableHash)] +pub struct ToolOptions { + pub reflectiveness: Reflectiveness, +} + +impl ToolOptions { + pub fn union(self, other: ToolOptions) -> Self { + ToolOptions { + reflectiveness: if self.reflectiveness == Reflective + || other.reflectiveness == Reflective + { + Reflective + } else { + NonReflective + }, + } + } +} + +pub type RegisteredTools = FxIndexMap; /// Declares a static item of type `&'static Lint`. /// @@ -703,23 +733,8 @@ macro_rules! declare_lint { #[allow_internal_unstable(default_field_values)] macro_rules! declare_tool_lint { ( - $(#[$attr:meta])* $vis:vis $tool:ident ::$NAME:ident, $Level: ident, $desc: expr - $(, @eval_always = $eval_always:literal)? - $(, @feature_gate = $gate:ident;)? - ) => ( - $crate::declare_tool_lint!{$(#[$attr])* $vis $tool::$NAME, $Level, $desc, false $(, @eval_always = $eval_always)? $(, @feature_gate = $gate;)?} - ); - ( - $(#[$attr:meta])* $vis:vis $tool:ident ::$NAME:ident, $Level:ident, $desc:expr, - report_in_external_macro: $rep:expr - $(, @eval_always = $eval_always: literal)? - $(, @feature_gate = $gate:ident;)? - ) => ( - $crate::declare_tool_lint!{$(#[$attr])* $vis $tool::$NAME, $Level, $desc, $rep $(, @eval_always = $eval_always)? $(, @feature_gate = $gate;)?} - ); - ( - $(#[$attr:meta])* $vis:vis $tool:ident ::$NAME:ident, $Level:ident, $desc:expr, - $external:expr + $(#[$attr:meta])* $vis:vis $tool:ident ::$NAME:ident, $Level:ident, $desc:expr + $(, @report_in_external_macro = $external:literal)? $(, @eval_always = $eval_always: literal)? $(, @feature_gate = $gate:ident;)? ) => ( @@ -728,7 +743,7 @@ macro_rules! declare_tool_lint { name: &concat!(stringify!($tool), "::", stringify!($NAME)), default_level: $crate::$Level, desc: $desc, - report_in_external_macro: $external, + $(report_in_external_macro: $external,)? is_externally_loaded: true, $(feature_gate: Some(rustc_span::sym::$gate),)? $(eval_always: $eval_always,)? diff --git a/compiler/rustc_metadata/src/creader.rs b/compiler/rustc_metadata/src/creader.rs index 30e04eef29704..505cb52001174 100644 --- a/compiler/rustc_metadata/src/creader.rs +++ b/compiler/rustc_metadata/src/creader.rs @@ -380,6 +380,11 @@ impl CStore { } let extern_crate = data.name(); + let emit = |mut diag: rustc_errors::Diag<'_>| { + diag.help(format!("if you are sure this will not cause problems, you may use `-Cunsafe-allow-abi-mismatch={opt_name}` to silence this {}", diag.level())); + diag.emit(); + }; + if prefix.is_empty() { // A synthetic target modifier, does not correspond to an actual flag. match opt_name.as_str() { @@ -426,8 +431,7 @@ impl CStore { let after = if extern_features.len() == 1 { "is" } else { "are" }; diag.help(format!("the target {before} {features} {after} enabled in `{extern_crate}` but disabled in this crate")); } - diag.help("if you are sure this will not cause problems, you may use `-Cunsafe-allow-abi-mismatch=target-feature` to silence this warning"); - diag.emit(); + emit(diag); } "codegen-backend-name" => { let diag = format!( @@ -436,50 +440,79 @@ impl CStore { let mut diag = tcx.dcx().struct_err(diag); diag.help("this crate has `-Zllvm-target-feature` set, which means different codegen backends could interpret the target features differently, or ignore them entirely"); diag.help("some target features modify the ABI so Rust crates compiled with different target features cannot be used together safely"); - diag.help("if you are sure this will not cause problems, you may use `-Cunsafe-allow-abi-mismatch=codegen-backend-name` to silence this warning"); - diag.emit(); + emit(diag) } _ => panic!("unhandled synthetic target feature {opt_name}"), } return; } - let flag_name = opt_name.clone(); let flag_name_prefixed = format!("-{}{}", prefix, opt_name); + let diag = format!( + "mixing `{flag_name_prefixed}` will cause an ABI mismatch in crate `{local_crate}`" + ); + let mut diag = tcx.dcx().struct_err(diag); + diag.help(format!( + "the `{flag_name_prefixed}` flag modifies the ABI so Rust crates compiled \ + with different values of this flag cannot be used together safely" + )); + match (flag_local_value, flag_extern_value) { (Some(local_value), Some(extern_value)) => { - tcx.dcx().emit_err(diagnostics::IncompatibleTargetModifiers { - extern_crate, - local_crate, - flag_name, - flag_name_prefixed, - local_value: local_value.to_string(), - extern_value: extern_value.to_string(), - }) + diag.note(format!( + "`{flag_name_prefixed}={local_value}` in this crate is incompatible \ + with `{flag_name_prefixed}={extern_value}` in dependency `{extern_crate}`" + )); + diag.help(format!( + "set `{flag_name_prefixed}={extern_value}` in this crate \ + or `{flag_name_prefixed}={local_value}` in `{extern_crate}`" + )); } (None, Some(extern_value)) => { - tcx.dcx().emit_err(diagnostics::IncompatibleTargetModifiersLMissed { - extern_crate, - local_crate, - flag_name, - flag_name_prefixed, - extern_value: extern_value.to_string(), - has_extern_value: !extern_value.is_empty(), - }) + let has_extern_value = !extern_value.is_empty(); + diag.note(format!( + "`{flag_name_prefixed}` is unset in this crate which is \ + incompatible with {} in dependency `{extern_crate}`", + if has_extern_value { + format!("`{flag_name_prefixed}={extern_value}`") + } else { + format!("`{flag_name_prefixed}` being set") + } + )); + diag.help(format!( + "set {} in this crate or unset `{flag_name_prefixed}` in `{extern_crate}`", + if has_extern_value { + format!("`{flag_name_prefixed}={extern_value}`") + } else { + format!("`{flag_name_prefixed}`") + } + )); } (Some(local_value), None) => { - tcx.dcx().emit_err(diagnostics::IncompatibleTargetModifiersRMissed { - extern_crate, - local_crate, - flag_name, - flag_name_prefixed, - local_value: local_value.to_string(), - has_local_value: !local_value.is_empty(), - }) + let has_local_value = !local_value.is_empty(); + diag.note(format!( + "{} in this crate is incompatible with \ + `{flag_name_prefixed}` being unset in dependency `{extern_crate}`", + if has_local_value { + format!("`{flag_name_prefixed}={local_value}`") + } else { + format!("`{flag_name_prefixed}` being set") + } + )); + diag.help(format!( + "unset `{flag_name_prefixed}` in this crate or set {} in `{extern_crate}`", + if has_local_value { + format!("`{flag_name_prefixed}={local_value}`") + } else { + format!("`{flag_name_prefixed}`") + } + )); } (None, None) => panic!("Incorrect target modifiers report_diff(None, None)"), }; + + emit(diag); }; let mut it1 = mods.iter().map(tmod_extender); let mut it2 = dep_mods.iter().map(tmod_extender); diff --git a/compiler/rustc_metadata/src/diagnostics.rs b/compiler/rustc_metadata/src/diagnostics.rs index 2f061c6f2f92c..4c46b7c5ed94d 100644 --- a/compiler/rustc_metadata/src/diagnostics.rs +++ b/compiler/rustc_metadata/src/diagnostics.rs @@ -577,96 +577,6 @@ pub(crate) struct WasmCAbi { pub span: Span, } -#[derive(Diagnostic)] -#[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(crate) struct IncompatibleTargetModifiers { - pub extern_crate: Symbol, - pub local_crate: Symbol, - pub flag_name: String, - pub flag_name_prefixed: String, - pub local_value: String, - pub extern_value: String, -} - -#[derive(Diagnostic)] -#[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}` is unset in this crate which is incompatible with {$has_extern_value -> - [false] `{$flag_name_prefixed}` being set - *[other] `{$flag_name_prefixed}={$extern_value}` - } in dependency `{$extern_crate}`" -)] -#[help( - "set {$has_extern_value -> - [false] `{$flag_name_prefixed}` - *[other] `{$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(crate) struct IncompatibleTargetModifiersLMissed { - pub extern_crate: Symbol, - pub local_crate: Symbol, - pub flag_name: String, - pub flag_name_prefixed: String, - pub extern_value: String, - pub has_extern_value: bool, -} - -#[derive(Diagnostic)] -#[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( - "{$has_local_value -> - [false] `{$flag_name_prefixed}` being set - *[other] `{$flag_name_prefixed}={$local_value}` - } in this crate is incompatible with `{$flag_name_prefixed}` being unset in dependency \ - `{$extern_crate}`" -)] -#[help( - "unset `{$flag_name_prefixed}` in this crate or set {$has_local_value -> - [false] `{$flag_name_prefixed}` - *[other] `{$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(crate) struct IncompatibleTargetModifiersRMissed { - pub extern_crate: Symbol, - pub local_crate: Symbol, - pub flag_name: String, - pub flag_name_prefixed: String, - pub local_value: String, - pub has_local_value: bool, -} - #[derive(Diagnostic)] #[diag( "unknown target modifier `{$flag_name}`, requested by \ diff --git a/compiler/rustc_metadata/src/rmeta/encoder.rs b/compiler/rustc_metadata/src/rmeta/encoder.rs index 3385f33b64989..cd65f566ce198 100644 --- a/compiler/rustc_metadata/src/rmeta/encoder.rs +++ b/compiler/rustc_metadata/src/rmeta/encoder.rs @@ -959,7 +959,7 @@ fn analyze_attr(attr: &rustc_attr_ir::Attribute, state: &mut AnalyzeAttrState) - true } Attribute::Parsed(p) => p.encode_cross_crate() == EncodeCrossCrate::Yes, - Attribute::Tool(_) | Attribute::DeriveHelper(_) => true, + Attribute::Tool { .. } | Attribute::DeriveHelper(_) => true, } } diff --git a/compiler/rustc_middle/src/hir/map.rs b/compiler/rustc_middle/src/hir/map.rs index a1f931290f827..5e65a9d57a20a 100644 --- a/compiler/rustc_middle/src/hir/map.rs +++ b/compiler/rustc_middle/src/hir/map.rs @@ -922,7 +922,7 @@ impl<'tcx> TyCtxt<'tcx> { name: &[Symbol], ) -> impl Iterator { self.hir_attrs(id).iter().filter_map(|attr| { - if let rustc_attr_ir::Attribute::Tool(t) = attr + if let rustc_attr_ir::Attribute::Tool { item: t, .. } = attr && *t.path.segments == *name { Some(&**t) diff --git a/compiler/rustc_middle/src/mir/pretty.rs b/compiler/rustc_middle/src/mir/pretty.rs index c93fb42bfe7eb..b8a1ebeee27fd 100644 --- a/compiler/rustc_middle/src/mir/pretty.rs +++ b/compiler/rustc_middle/src/mir/pretty.rs @@ -573,8 +573,9 @@ fn write_coroutine_layout<'tcx>( w: &mut dyn io::Write, options: PrettyPrintMirOptions, ) -> io::Result<()> { - let CoroutineLayout { field_tys, variant_fields, variant_source_info, storage_conflicts } = - layout; + let CoroutineLayout { + field_tys, variant_fields, variant_source_info, storage_conflicts, .. + } = layout; writeln!(w, "{INDENT}coroutine layout {{")?; diff --git a/compiler/rustc_middle/src/mir/query.rs b/compiler/rustc_middle/src/mir/query.rs index 2e84fd80f35e5..062209b6e2fdd 100644 --- a/compiler/rustc_middle/src/mir/query.rs +++ b/compiler/rustc_middle/src/mir/query.rs @@ -2,7 +2,7 @@ use std::fmt::{self, Debug}; -use rustc_abi::{FieldIdx, VariantIdx}; +use rustc_abi::{FieldIdx, PackCoroutineLayout, VariantIdx}; use rustc_errors::ErrorGuaranteed; use rustc_index::IndexVec; use rustc_index::bit_set::BitMatrix; @@ -53,6 +53,11 @@ pub struct CoroutineLayout<'tcx> { #[type_foldable(identity)] #[type_visitable(ignore)] pub storage_conflicts: BitMatrix, + + /// Coroutine layout packing + #[type_foldable(identity)] + #[type_visitable(ignore)] + pub pack: PackCoroutineLayout, } impl Debug for CoroutineLayout<'_> { diff --git a/compiler/rustc_middle/src/ty/mod.rs b/compiler/rustc_middle/src/ty/mod.rs index 5a5213be8bda1..d61e2bcbdd221 100644 --- a/compiler/rustc_middle/src/ty/mod.rs +++ b/compiler/rustc_middle/src/ty/mod.rs @@ -1924,7 +1924,7 @@ impl<'tcx> TyCtxt<'tcx> { ) -> impl Iterator { #[expect(deprecated)] self.get_all_attrs(did).iter().filter_map(|attr| { - if let rustc_attr_ir::Attribute::Tool(t) = attr + if let rustc_attr_ir::Attribute::Tool { item: t, .. } = attr && *t.path.segments == *name { Some(&**t) @@ -2061,6 +2061,8 @@ impl<'tcx> TyCtxt<'tcx> { variant_fields, variant_source_info, storage_conflicts: BitMatrix::new(0, 0), + // FIXME(-Zpack-coroutine-layout): Stop ignoring the flag here. + pack: rustc_abi::PackCoroutineLayout::Classic, }; return Ok(self.arena.alloc(proxy_layout)); } else { diff --git a/compiler/rustc_mir_transform/src/coroutine/layout.rs b/compiler/rustc_mir_transform/src/coroutine/layout.rs index d0c236c4d53a6..4d955ecfed275 100644 --- a/compiler/rustc_mir_transform/src/coroutine/layout.rs +++ b/compiler/rustc_mir_transform/src/coroutine/layout.rs @@ -23,7 +23,7 @@ use std::ops; use itertools::izip; -use rustc_abi::{FieldIdx, VariantIdx}; +use rustc_abi::{FieldIdx, PackCoroutineLayout, VariantIdx}; use rustc_attr_ir::find_attr; use rustc_attr_ir::lang_items::LangItem; use rustc_data_structures::fx::FxHashSet; @@ -443,8 +443,14 @@ pub(super) fn compute_layout<'tcx>( tys[saved_local].debuginfo_name.get_or_insert(var.name); } - let layout = - CoroutineLayout { field_tys: tys, variant_fields, variant_source_info, storage_conflicts }; + let layout = CoroutineLayout { + field_tys: tys, + variant_fields, + variant_source_info, + storage_conflicts, + // FIXME(-Zpack-coroutine-layout): Stop ignoring the flag here. + pack: PackCoroutineLayout::Classic, + }; debug!(?remap); debug!(?layout); debug!(?storage_liveness); diff --git a/compiler/rustc_passes/src/check_attr.rs b/compiler/rustc_passes/src/check_attr.rs index 1c177071d37c0..5dd1718d68d49 100644 --- a/compiler/rustc_passes/src/check_attr.rs +++ b/compiler/rustc_passes/src/check_attr.rs @@ -136,7 +136,7 @@ impl<'tcx> CheckAttrVisitor<'tcx> { Attribute::Parsed(attr_kind) => { self.check_one_parsed_attribute(hir_id, span, target, item, attr_kind); } - Attribute::Tool(u) | Attribute::DeriveHelper(u) => { + Attribute::Tool { item: u, .. } | Attribute::DeriveHelper(u) => { match &*u.path.segments { [name, rest @ ..] => { if BUILTIN_ATTRIBUTE_SET.contains(name) { diff --git a/compiler/rustc_passes/src/dead.rs b/compiler/rustc_passes/src/dead.rs index 6cd8e254b503f..7f5b29bf5be25 100644 --- a/compiler/rustc_passes/src/dead.rs +++ b/compiler/rustc_passes/src/dead.rs @@ -1019,62 +1019,7 @@ fn maybe_record_as_seed<'tcx>( push_into_worklist: &mut impl FnMut(WorkItem), unsolved_items: &mut Vec, ) { - let allow_dead_code = has_allow_dead_code_or_lang_attr(tcx, owner_id.def_id); - if let Some(comes_from_allow) = allow_dead_code { - push_into_worklist(WorkItem { - id: owner_id.def_id, - propagated: comes_from_allow, - own: comes_from_allow, - propagated_trivial_usage_site: None, - }); - } - match tcx.def_kind(owner_id) { - DefKind::Enum => { - if let Some(comes_from_allow) = allow_dead_code { - let adt = tcx.adt_def(owner_id); - for variant in adt.variants().iter() { - push_into_worklist(WorkItem { - id: variant.def_id.expect_local(), - propagated: comes_from_allow, - own: comes_from_allow, - propagated_trivial_usage_site: None, - }); - } - } - } - DefKind::AssocFn | DefKind::AssocConst | DefKind::AssocTy => { - // As with free constants named `_`, associated constants named `_` are always live. - if let hir::Node::ImplItem(impl_item) = tcx.hir_node_by_def_id(owner_id.def_id) - && impl_item.is_anon_const() - { - push_into_worklist(WorkItem { - id: owner_id.def_id, - propagated: ComesFromAllowExpect::No, - own: ComesFromAllowExpect::No, - propagated_trivial_usage_site: None, - }); - } - - if allow_dead_code.is_none() { - let parent = tcx.local_parent(owner_id.def_id); - match tcx.def_kind(parent) { - DefKind::Impl { of_trait: false } | DefKind::Trait => {} - DefKind::Impl { of_trait: true } => { - // We only care about associated items of traits, - // because they cannot be visited directly, - // so we later mark them as live if their corresponding traits - // or trait items and self types are both live, - // but inherent associated items can be visited and marked directly. - unsolved_items.push(owner_id.def_id); - } - _ => bug!(), - } - } - } - DefKind::Impl { of_trait: true } if allow_dead_code.is_none() => { - unsolved_items.push(owner_id.def_id); - } DefKind::GlobalAsm => { // global_asm! is always live. push_into_worklist(WorkItem { @@ -1084,19 +1029,59 @@ fn maybe_record_as_seed<'tcx>( propagated_trivial_usage_site: None, }); } - DefKind::Const => { - if tcx.item_name(owner_id.def_id) == kw::Underscore { - // `const _` is always live, as that syntax only exists for the side effects - // of type checking and evaluating the constant expression, and marking them - // as dead code would defeat that purpose. - push_into_worklist(WorkItem { - id: owner_id.def_id, - propagated: ComesFromAllowExpect::No, - own: ComesFromAllowExpect::No, - propagated_trivial_usage_site: None, - }); + DefKind::Const if tcx.item_name(owner_id.def_id) == kw::Underscore => { + // `const _` is always live, as that syntax only exists for the side effects + // of type checking and evaluating the constant expression, and marking them + // as dead code would defeat that purpose. + push_into_worklist(WorkItem { + id: owner_id.def_id, + propagated: ComesFromAllowExpect::No, + own: ComesFromAllowExpect::No, + propagated_trivial_usage_site: None, + }); + } + DefKind::AssocFn | DefKind::AssocConst | DefKind::AssocTy + if let hir::Node::ImplItem(impl_item) = tcx.hir_node_by_def_id(owner_id.def_id) + && impl_item.is_anon_const() => + { + // As with free constants named `_`, associated constants named `_` are always live. + push_into_worklist(WorkItem { + id: owner_id.def_id, + propagated: ComesFromAllowExpect::No, + own: ComesFromAllowExpect::No, + propagated_trivial_usage_site: None, + }); + } + + _ if let Some(comes_from_allow) = + has_allow_dead_code_or_lang_attr(tcx, owner_id.def_id) => + { + push_into_worklist(WorkItem { + id: owner_id.def_id, + propagated: comes_from_allow, + own: comes_from_allow, + propagated_trivial_usage_site: None, + }); + } + + DefKind::AssocFn | DefKind::AssocConst | DefKind::AssocTy => { + let parent = tcx.local_parent(owner_id.def_id); + match tcx.def_kind(parent) { + DefKind::Impl { of_trait: false } | DefKind::Trait => {} + DefKind::Impl { of_trait: true } => { + // We only care about associated items of traits, + // because they cannot be visited directly, + // so we later mark them as live if their corresponding traits + // or trait items and self types are both live, + // but inherent associated items can be visited and marked directly. + unsolved_items.push(owner_id.def_id); + } + _ => bug!(), } } + DefKind::Impl { of_trait: true } => { + unsolved_items.push(owner_id.def_id); + } _ => {} } } diff --git a/compiler/rustc_public_bridge/src/context/impls.rs b/compiler/rustc_public_bridge/src/context/impls.rs index 8c9c6ec3001c2..1ae42f619c4ba 100644 --- a/compiler/rustc_public_bridge/src/context/impls.rs +++ b/compiler/rustc_public_bridge/src/context/impls.rs @@ -310,9 +310,9 @@ impl<'tcx, B: Bridge> CompilerCtxt<'tcx, B> { }; attrs_iter .filter_map(|attribute| { - if let Attribute::Tool(u) = attribute { + if let Attribute::Tool { item, .. } = attribute { let attr_str = rustc_hir_pretty::attribute_to_string(self, attribute); - Some((attr_str, u.span)) + Some((attr_str, item.span)) } else { None } diff --git a/compiler/rustc_resolve/src/diagnostics/impls.rs b/compiler/rustc_resolve/src/diagnostics/impls.rs index 7b4ecee52dad1..271a88e626ea0 100644 --- a/compiler/rustc_resolve/src/diagnostics/impls.rs +++ b/compiler/rustc_resolve/src/diagnostics/impls.rs @@ -1601,7 +1601,7 @@ impl<'ra, 'tcx> Resolver<'ra, 'tcx> { suggestions.extend( this.registered_attr_tools .iter() - .map(|ident| TypoSuggestion::new(ident.name, ident.span, res)), + .map(|(tool, _)| TypoSuggestion::new(tool.name, tool.span, res)), ); } Scope::StdLibPrelude => { diff --git a/compiler/rustc_resolve/src/lib.rs b/compiler/rustc_resolve/src/lib.rs index 0fc9c31f43e32..ef368af85f017 100644 --- a/compiler/rustc_resolve/src/lib.rs +++ b/compiler/rustc_resolve/src/lib.rs @@ -1901,10 +1901,10 @@ impl<'ra, 'tcx> Resolver<'ra, 'tcx> { .collect(), registered_attr_tool_decls: registered_attr_tools .iter() - .map(|&ident| { + .map(|(&tool, _)| { let res = Res::ToolMod; - let decl = arenas.new_pub_def_decl(res, ident.span, LocalExpnId::ROOT); - (IdentKey::new(ident), decl) + let decl = arenas.new_pub_def_decl(res, tool.span, LocalExpnId::ROOT); + (IdentKey::new(tool), decl) }) .collect(), registered_attr_tools, diff --git a/compiler/rustc_resolve/src/macros.rs b/compiler/rustc_resolve/src/macros.rs index b809911045341..e8261f2ff12d7 100644 --- a/compiler/rustc_resolve/src/macros.rs +++ b/compiler/rustc_resolve/src/macros.rs @@ -7,7 +7,7 @@ use std::sync::Arc; use rustc_ast::{self as ast, Crate, DelegationSuffixes, NodeId}; use rustc_ast_pretty::pprust; use rustc_attr_ir::{Attribute, AttributeKind, CfgEntry, StabilityLevel, StrippedCfgItem}; -use rustc_attr_parsing::AttributeParser; +use rustc_attr_parsing::{AttributeParser, PREDEFINED_TOOLS}; use rustc_data_structures::sync::RwLock; use rustc_errors::{Applicability, StashKey}; use rustc_expand::base::{ @@ -23,6 +23,7 @@ use rustc_hir::def_id::{CrateNum, DefId, LocalDefId}; use rustc_lint_defs::builtin::{ LEGACY_DERIVE_HELPERS, OUT_OF_SCOPE_MACRO_CALLS, UNUSED_MACRO_RULES, UNUSED_MACROS, }; +use rustc_lint_defs::{Reflectiveness, ToolOptions}; use rustc_middle::middle::stability; use rustc_middle::ty::{RegisteredTools, TyCtxt}; use rustc_session::Session; @@ -120,9 +121,6 @@ fn fast_print_path(path: &ast::Path) -> Symbol { } } -const PREDEFINED_TOOLS: &[Symbol] = - &[sym::clippy, sym::rustfmt, sym::diagnostic, sym::miri, sym::rust_analyzer]; - pub(crate) fn registered_attr_tools(tcx: TyCtxt<'_>, (): ()) -> RegisteredTools { let (_, pre_configured_attrs) = &*tcx.crate_for_resolver(()).borrow(); @@ -139,13 +137,9 @@ pub(crate) fn registered_attr_tools(tcx: TyCtxt<'_>, (): ()) -> RegisteredTools }; // We implicitly add predefined tools, but it's not an error to register them explicitly. - - // FIXME this should instead be using tool attribute imports or something similar - if tcx.features().type_info() { - registered_tools.insert(Ident::with_dummy_span(sym::reflection_placeholder)); - } - - registered_tools.extend(PREDEFINED_TOOLS.iter().cloned().map(Ident::with_dummy_span)); + registered_tools.extend(PREDEFINED_TOOLS.iter().cloned().map(|n| { + (Ident::with_dummy_span(n), ToolOptions { reflectiveness: Reflectiveness::NonReflective }) + })); registered_tools } @@ -171,7 +165,12 @@ pub fn registered_lint_tools_ast( }; // We implicitly add predefined tools, but it's not an error to register them explicitly. - registered_tools.extend(PREDEFINED_TOOLS.iter().cloned().map(Ident::with_dummy_span)); + registered_tools.extend(PREDEFINED_TOOLS.iter().cloned().map(|ident| { + ( + Ident::with_dummy_span(ident), + ToolOptions { reflectiveness: Reflectiveness::NonReflective }, + ) + })); registered_tools } diff --git a/compiler/rustc_session/src/config.rs b/compiler/rustc_session/src/config.rs index d9c2c6a5a9eb2..0975423ecf363 100644 --- a/compiler/rustc_session/src/config.rs +++ b/compiler/rustc_session/src/config.rs @@ -3504,7 +3504,7 @@ pub(crate) mod dep_tracking { use std::num::NonZero; use std::path::PathBuf; - use rustc_abi::Align; + use rustc_abi::{Align, PackCoroutineLayout}; use rustc_ast::attr::version::RustcVersion; use rustc_data_structures::fx::FxIndexMap; use rustc_data_structures::stable_hash::{DummyStableHashCtxt, StableHash, StableHasher}; @@ -3610,6 +3610,7 @@ pub(crate) mod dep_tracking { OptLevel, OutFileName, OutputType, + PackCoroutineLayout, PanicStrategy, PatchableFunctionEntry, PointerAuthOption, diff --git a/compiler/rustc_session/src/diagnostics.rs b/compiler/rustc_session/src/diagnostics.rs index 53a0fde70b089..26239df3028f9 100644 --- a/compiler/rustc_session/src/diagnostics.rs +++ b/compiler/rustc_session/src/diagnostics.rs @@ -721,6 +721,10 @@ pub(crate) struct ThinLtoNotSupportedByBackend; #[diag("`-Zpacked-stack` is only supported on s390x")] pub(crate) struct UnsupportedPackedStack; +#[derive(Diagnostic)] +#[diag("`-Z pack-coroutine-layout=captures-only` is not yet implemented and will be ignored")] +pub(crate) struct PackCoroutineLayoutNotImplemented; + #[derive(Diagnostic)] #[diag("`-Ctarget-cpu=native` is not allowed for target `{$target_triple}`")] #[note("this target requires consistent `-Ctarget-cpu` values across all crates")] diff --git a/compiler/rustc_session/src/options.rs b/compiler/rustc_session/src/options.rs index e599394dfcfdc..326323b727a04 100644 --- a/compiler/rustc_session/src/options.rs +++ b/compiler/rustc_session/src/options.rs @@ -3,7 +3,7 @@ use std::num::{IntErrorKind, NonZero}; use std::path::PathBuf; use std::str; -use rustc_abi::Align; +use rustc_abi::{Align, PackCoroutineLayout}; use rustc_ast::attr::version::RustcVersion; use rustc_data_structures::profiling::TimePassesFormat; use rustc_data_structures::stable_hash::StableHasher; @@ -70,8 +70,8 @@ pub struct ExtendedTargetModifierInfo { /// Flag prefix (usually, 'C' for codegen flags or 'Z' for unstable flags). And empty string /// indicates a synthetic target modifier, which does not correspond directly to a flag. pub prefix: String, - /// Flag name. For synthetic features, this is still relevant as the name used to suppress - /// the error for mismatches involving this target modifier. + /// Flag name. For synthetic target modifiers, this is still relevant as the name is used with + /// `-Cunsafe-allow-abi-mismatch`. pub name: String, /// Flag parsed technical value pub tech_value: String, @@ -916,6 +916,7 @@ mod desc { pub(crate) const parse_panic_strategy: &str = "either `unwind`, `abort`, or `immediate-abort`"; pub(crate) const parse_on_broken_pipe: &str = "either `kill`, `error`, or `inherit`"; pub(crate) const parse_patchable_function_entry: &str = "a comma separated list of (prefix_nops,total_nops,section_name), (prefix_nops,total_nops), or (total_nops). Where prefix_nops <= total_nops where 0 < total_nops <= 255 and prefix_nops <= total_nops"; + pub(crate) const parse_pack_coroutine_layout: &str = "either `classic` or `captures-only`"; pub(crate) const parse_opt_panic_strategy: &str = parse_panic_strategy; pub(crate) const parse_relro_level: &str = "one of: `full`, `partial`, or `off`"; pub(crate) const parse_sanitizers: &str = "comma separated list of sanitizers: `address`, `cfi`, `dataflow`, `hwaddress`, `kcfi`, `kernel-address`, `kernel-hwaddress`, `leak`, `memory`, `memtag`, `safestack`, `shadow-call-stack`, `thread`, or 'realtime'"; @@ -2177,6 +2178,18 @@ pub mod parse { true } + pub(crate) fn parse_pack_coroutine_layout( + slot: &mut PackCoroutineLayout, + v: Option<&str>, + ) -> bool { + *slot = match v { + Some("classic") => PackCoroutineLayout::Classic, + Some("captures-only") => PackCoroutineLayout::CapturesOnly, + _ => return false, + }; + true + } + pub(crate) fn parse_inlining_threshold(slot: &mut InliningThreshold, v: Option<&str>) -> bool { match v { Some("always" | "yes") => { @@ -2822,6 +2835,8 @@ options! { "behavior of std::io::ErrorKind::BrokenPipe (SIGPIPE)"), osx_rpath_install_name: bool = (false, parse_bool, [TRACKED], "pass `-install_name @rpath/...` to the macOS linker (default: no)"), + pack_coroutine_layout: PackCoroutineLayout = (PackCoroutineLayout::default(), parse_pack_coroutine_layout, [TRACKED], + "set strategy to pack coroutine state layout (default: classic)"), packed_bundled_libs: bool = (false, parse_bool, [TRACKED], "change rlib format to store native libraries as archives"), packed_stack: bool = (false, parse_bool, [TRACKED], diff --git a/compiler/rustc_session/src/session.rs b/compiler/rustc_session/src/session.rs index 2b23284c55f57..6b7e2214f26d9 100644 --- a/compiler/rustc_session/src/session.rs +++ b/compiler/rustc_session/src/session.rs @@ -7,6 +7,7 @@ use std::sync::Arc; use std::sync::atomic::{AtomicBool, AtomicUsize}; use std::{env, io}; +use rustc_abi::PackCoroutineLayout; use rustc_data_structures::flock; use rustc_data_structures::fx::{FxHashMap, FxHashSet, FxIndexSet}; use rustc_data_structures::profiling::{SelfProfiler, SelfProfilerRef}; @@ -1861,6 +1862,13 @@ fn validate_commandline_args_with_session_available(sess: &Session) { } } + match sess.opts.unstable_opts.pack_coroutine_layout { + PackCoroutineLayout::Classic => {} + PackCoroutineLayout::CapturesOnly => { + sess.dcx().emit_warn(diagnostics::PackCoroutineLayoutNotImplemented); + } + } + if let Some(ref cpu_name) = sess.opts.cg.target_cpu { if cpu_name == NATIVE_CPU && sess.target.requires_consistent_cpu { sess.dcx().emit_fatal(diagnostics::NativeTargetCpuNotAllowed { diff --git a/compiler/rustc_target/src/callconv/arm.rs b/compiler/rustc_target/src/callconv/arm.rs index 9a946d6ae0c75..097d6a1f0f8ae 100644 --- a/compiler/rustc_target/src/callconv/arm.rs +++ b/compiler/rustc_target/src/callconv/arm.rs @@ -25,9 +25,9 @@ where let valid_unit = match unit.kind { RegKind::Integer => false, - RegKind::Float => true, - RegKind::PpcF128 => unreachable!(), + RegKind::Float => unit.size.bits() == 32 || unit.size.bits() == 64, RegKind::Vector { .. } => unit.size.bits() == 64 || unit.size.bits() == 128, + RegKind::PpcF128 => unreachable!(), }; valid_unit.then_some(Uniform::consecutive(unit, size)) diff --git a/library/core/src/mem/type_info.rs b/library/core/src/mem/type_info.rs index 5edca89d4c759..1ad39e3c2f3ac 100644 --- a/library/core/src/mem/type_info.rs +++ b/library/core/src/mem/type_info.rs @@ -658,18 +658,20 @@ impl TypeId { } /// Given given a `TypeId`, which represents a structure, enum or union returns a list of attributes. - /// Only the attributes of the tool `reflection_placeholder` are returned, all other attributes are excluded. + /// Only the attributes of tools marked as `reflect` are returned, all other attributes are excluded. /// The attributes are in a string representation. /// /// ``` /// #![feature(type_info)] + /// #![feature(register_tool)] + /// #![register_tool(foo(reflect))] /// # use std::any::TypeId; /// - /// #[reflection_placeholder::a(1, false)] - /// #[reflection_placeholder::foo=123] + /// #[foo::a(1, false)] + /// #[foo::bar=123] /// struct A; /// - /// assert_eq!(const { TypeId::of::().reflected_attrs() }, ["#[reflection_placeholder::a(1, false)]", "#[reflection_placeholder::foo = 123]"]); + /// assert_eq!(const { TypeId::of::().reflected_attrs() }, ["#[foo::a(1, false)]", "#[foo::bar = 123]"]); /// ``` #[unstable(feature = "type_info", issue = "146922")] #[rustc_const_unstable(feature = "type_info", issue = "146922")] @@ -728,21 +730,23 @@ impl VariantId { } /// Given given a `VariantId` returns a list of attributes. - /// Only the attributes of the tool `reflection_placeholder` are returned, all other attributes are excluded. + /// Only the attributes of tools marked as `reflect` are returned, all other attributes are excluded. /// The attributes are in a string representation. /// /// ``` /// #![feature(type_info)] + /// #![feature(register_tool)] + /// #![register_tool(foo(reflect))] /// # use std::any::TypeId; /// /// enum A { - /// #[reflection_placeholder::a(1, false)] - /// #[reflection_placeholder::foo=123] + /// #[foo::a(1, false)] + /// #[foo::bar=123] /// VarA, /// VarB, /// } /// - /// assert_eq!(const { TypeId::of::().variant(0).reflected_attrs() }, &["#[reflection_placeholder::a(1, false)]", "#[reflection_placeholder::foo = 123]"]); + /// assert_eq!(const { TypeId::of::().variant(0).reflected_attrs() }, &["#[foo::a(1, false)]", "#[foo::bar = 123]"]); /// ``` #[unstable(feature = "type_info", issue = "146922")] #[rustc_const_unstable(feature = "type_info", issue = "146922")] @@ -835,20 +839,22 @@ impl FieldId { } /// Given given a `FieldId` returns a list of attributes. - /// Only the attributes of the tool `reflection_placeholder` are returned, all other attributes are excluded. + /// Only the attributes of tools marked as `reflect` are returned, all other attributes are excluded. /// The attributes are in a string representation. /// /// ``` /// #![feature(type_info)] + /// #![feature(register_tool)] + /// #![register_tool(foo(reflect))] /// # use std::any::TypeId; /// /// struct A { - /// #[reflection_placeholder::a(1, false)] - /// #[reflection_placeholder::foo=123] + /// #[foo::a(1, false)] + /// #[foo::bar=123] /// first: u8, /// } /// - /// assert_eq!(const { TypeId::of::().field(0, 0).reflected_attrs() }, &["#[reflection_placeholder::a(1, false)]", "#[reflection_placeholder::foo = 123]"]); + /// assert_eq!(const { TypeId::of::().field(0, 0).reflected_attrs() }, &["#[foo::a(1, false)]", "#[foo::bar = 123]"]); /// ``` #[unstable(feature = "type_info", issue = "146922")] #[rustc_const_unstable(feature = "type_info", issue = "146922")] diff --git a/library/coretests/tests/lib.rs b/library/coretests/tests/lib.rs index 3a5c051eee16e..3e79c88a116e3 100644 --- a/library/coretests/tests/lib.rs +++ b/library/coretests/tests/lib.rs @@ -106,6 +106,7 @@ #![feature(portable_simd)] #![feature(ptr_metadata)] #![feature(raw_os_error_ty)] +#![feature(register_tool)] #![feature(rustc_attrs)] #![feature(signed_bigint_helpers)] #![feature(slice_from_ptr_range)] @@ -139,6 +140,7 @@ #![allow(internal_features)] #![deny(implicit_provenance_casts)] #![deny(unsafe_op_in_unsafe_fn)] +#![register_tool(reflective_tool(reflect))] // to allow testing of attribute reflection in `mem/type_info.rs` /// Version of `assert_matches` that ignores fancy runtime printing in const context and uses structural equality. macro_rules! assert_eq_const_safe { diff --git a/library/coretests/tests/mem/type_info.rs b/library/coretests/tests/mem/type_info.rs index 34128bc4d8d63..76e2adad18f1c 100644 --- a/library/coretests/tests/mem/type_info.rs +++ b/library/coretests/tests/mem/type_info.rs @@ -57,12 +57,12 @@ fn test_tuples() { #[test] fn test_structs() { const { - #[reflection_placeholder::TestStruct] + #[reflective_tool::TestStruct] struct TestStruct { - #[reflection_placeholder::first(1)] - #[reflection_placeholder::first(2)] + #[reflective_tool::first(1)] + #[reflective_tool::first(2)] first: u8, - #[reflection_placeholder::second] + #[reflective_tool::second] second: u16, reference: &'static u16, } @@ -70,7 +70,7 @@ fn test_structs() { let ty_id = TypeId::of::(); assert!(!ty_id.non_exhaustive()); assert!(ty_id.size() == Some(size_of::())); - assert!(ty_id.reflected_attrs() == &["#[reflection_placeholder::TestStruct]"]); + assert!(ty_id.reflected_attrs() == &["#[reflective_tool::TestStruct]"]); assert!(ty_id.variants() == 1); assert!(ty_id.fields(0) == 3); assert!(ty_id.field(0, 0).type_id() == TypeId::of::()); @@ -78,12 +78,12 @@ fn test_structs() { assert!(ty_id.field(0, 0).name() == "first"); assert!( ty_id.field(0, 0).reflected_attrs() - == &["#[reflection_placeholder::first(1)]", "#[reflection_placeholder::first(2)]"] + == &["#[reflective_tool::first(1)]", "#[reflective_tool::first(2)]"] ); assert!(ty_id.field(0, 1).type_id() == TypeId::of::()); assert!(ty_id.field(0, 1).offset() == offset_of!(TestStruct, second)); assert!(ty_id.field(0, 1).name() == "second"); - assert!(ty_id.field(0, 1).reflected_attrs() == &["#[reflection_placeholder::second]"]); + assert!(ty_id.field(0, 1).reflected_attrs() == &["#[reflective_tool::second]"]); assert!(ty_id.field(0, 2).type_id() == TypeId::of::<&u16>()); assert!(ty_id.field(0, 2).offset() == offset_of!(TestStruct, reference)); assert!(ty_id.field(0, 2).name() == "reference"); @@ -112,7 +112,7 @@ fn test_structs() { } const { - #[reflection_placeholder::a] + #[reflective_tool::a] struct Generics<'a, T, const C: u64> { a: &'a T, } @@ -120,7 +120,7 @@ fn test_structs() { let ty_id = TypeId::of::>(); assert!(ty_id.fields(0) == 1); assert!(ty_id.generics().len() == 3); - assert!(ty_id.reflected_attrs() == &["#[reflection_placeholder::a]"]); + assert!(ty_id.reflected_attrs() == &["#[reflective_tool::a]"]); let Generic::Lifetime(_) = ty_id.generics()[0] else { panic!() }; let Generic::Type(GenericType { ty: generic_ty, .. }) = ty_id.generics()[1] else { @@ -135,11 +135,11 @@ fn test_structs() { #[test] fn test_unions() { const { - #[reflection_placeholder::a] + #[reflective_tool::a] union TestUnion { - #[reflection_placeholder::first] + #[reflective_tool::first] first: i16, - #[reflection_placeholder::second] + #[reflective_tool::second] second: u16, } @@ -147,17 +147,17 @@ fn test_unions() { assert!(ty_id.size() == Some(size_of::())); assert!(ty_id.variants() == 1); assert!(ty_id.fields(0) == 2); - assert!(ty_id.reflected_attrs() == &["#[reflection_placeholder::a]"]); + assert!(ty_id.reflected_attrs() == &["#[reflective_tool::a]"]); assert!(ty_id.field(0, 0).name() == "first"); assert!(ty_id.field(0, 0).type_id() == TypeId::of::()); - assert!(ty_id.field(0, 0).reflected_attrs() == &["#[reflection_placeholder::first]"]); + assert!(ty_id.field(0, 0).reflected_attrs() == &["#[reflective_tool::first]"]); assert!(ty_id.field(0, 1).name() == "second"); assert!(ty_id.field(0, 1).type_id() == TypeId::of::()); - assert!(ty_id.field(0, 1).reflected_attrs() == &["#[reflection_placeholder::second]"]); + assert!(ty_id.field(0, 1).reflected_attrs() == &["#[reflective_tool::second]"]); } const { - #[reflection_placeholder::a] + #[reflective_tool::a] union Generics<'a, T: Copy, const C: u64> { a: T, z: &'a (), @@ -165,7 +165,7 @@ fn test_unions() { let ty_id = TypeId::of::>(); assert!(ty_id.fields(0) == 2); - assert!(ty_id.reflected_attrs() == &["#[reflection_placeholder::a]"]); + assert!(ty_id.reflected_attrs() == &["#[reflective_tool::a]"]); assert!(ty_id.field(0, 1).offset() == offset_of!(Generics<'static, i32, 1_u64>, a)); assert!(ty_id.field(0, 1).offset() == offset_of!(Generics<'static, i32, 1_u64>, z)); @@ -183,17 +183,17 @@ fn test_unions() { #[test] fn test_enums() { const { - #[reflection_placeholder::a] + #[reflective_tool::a] enum E { - #[reflection_placeholder::some] + #[reflective_tool::some] Some(u32), - #[reflection_placeholder::none] + #[reflective_tool::none] None, - #[reflection_placeholder::foomp] + #[reflective_tool::foomp] #[non_exhaustive] Foomp { a: (), - #[reflection_placeholder::b] + #[reflective_tool::b] b: &'static str, }, } @@ -201,28 +201,28 @@ fn test_enums() { let ty_id = TypeId::of::(); assert!(!ty_id.non_exhaustive()); assert!(ty_id.size() == Some(size_of::())); - assert!(ty_id.reflected_attrs() == &["#[reflection_placeholder::a]"]); + assert!(ty_id.reflected_attrs() == &["#[reflective_tool::a]"]); assert!(ty_id.variants() == 3); assert!(ty_id.variant(0).name() == "Some"); - assert!(ty_id.variant(0).reflected_attrs() == &["#[reflection_placeholder::some]"]); + assert!(ty_id.variant(0).reflected_attrs() == &["#[reflective_tool::some]"]); assert!(!ty_id.variant(0).non_exhaustive()); assert!(ty_id.fields(0) == 1); assert!(ty_id.field(0, 0).type_id() == TypeId::of::()); assert!(ty_id.variant(1).name() == "None"); - assert!(ty_id.variant(1).reflected_attrs() == &["#[reflection_placeholder::none]"]); + assert!(ty_id.variant(1).reflected_attrs() == &["#[reflective_tool::none]"]); assert!(!ty_id.variant(1).non_exhaustive()); assert!(ty_id.fields(1) == 0); assert!(ty_id.variant(2).name() == "Foomp"); - assert!(ty_id.variant(2).reflected_attrs() == &["#[reflection_placeholder::foomp]"]); + assert!(ty_id.variant(2).reflected_attrs() == &["#[reflective_tool::foomp]"]); assert!(ty_id.variant(2).non_exhaustive()); assert!(ty_id.fields(2) == 2); assert!(ty_id.field(2, 0).type_id() == TypeId::of::<()>()); assert!(ty_id.field(2, 1).type_id() == TypeId::of::<&str>()); assert!(ty_id.field(2, 1).name() == "b"); - assert!(ty_id.field(2, 1).reflected_attrs() == &["#[reflection_placeholder::b]"]); + assert!(ty_id.field(2, 1).reflected_attrs() == &["#[reflective_tool::b]"]); assert!(ty_id.generics().is_empty()); } diff --git a/src/bootstrap/src/core/build_steps/llvm.rs b/src/bootstrap/src/core/build_steps/llvm.rs index 0897fcd1dcc6f..34c9f20546bf0 100644 --- a/src/bootstrap/src/core/build_steps/llvm.rs +++ b/src/bootstrap/src/core/build_steps/llvm.rs @@ -1708,8 +1708,17 @@ impl CommandLineStep for Lld { let out_dir = builder.out.join(target).join("lld"); - let lld_stamp = BuildStamp::new(&out_dir).with_prefix("lld"); - if lld_stamp.path().exists() { + static STAMP_HASH_MEMO: OnceLock = OnceLock::new(); + let smart_stamp_hash = STAMP_HASH_MEMO.get_or_init(|| { + generate_smart_stamp_hash( + builder, + &builder.config.src.join("src/llvm-project"), + builder.in_tree_llvm_info.sha().unwrap_or_default(), + ) + }); + + let lld_stamp = BuildStamp::new(&out_dir).with_prefix("lld").add_stamp(smart_stamp_hash); + if lld_stamp.is_up_to_date() { return out_dir; } diff --git a/src/bootstrap/src/core/builder/cli_paths/snapshots/x_bench.snap b/src/bootstrap/src/core/builder/cli_paths/snapshots/x_bench.snap index c609f5ffd51fa..d0e0c03d9791b 100644 --- a/src/bootstrap/src/core/builder/cli_paths/snapshots/x_bench.snap +++ b/src/bootstrap/src/core/builder/cli_paths/snapshots/x_bench.snap @@ -31,7 +31,6 @@ expression: bench - Set({compiler/rustc_ast_pretty}) - Set({compiler/rustc_attr_ir}) - Set({compiler/rustc_attr_parsing}) - - Set({compiler/rustc_baked_icu_data}) - Set({compiler/rustc_borrowck}) - Set({compiler/rustc_builtin_macros}) - Set({compiler/rustc_codegen_llvm}) diff --git a/src/bootstrap/src/core/builder/cli_paths/snapshots/x_build_compiler.snap b/src/bootstrap/src/core/builder/cli_paths/snapshots/x_build_compiler.snap index 41529a664a189..653064633bf49 100644 --- a/src/bootstrap/src/core/builder/cli_paths/snapshots/x_build_compiler.snap +++ b/src/bootstrap/src/core/builder/cli_paths/snapshots/x_build_compiler.snap @@ -13,7 +13,6 @@ expression: build compiler - Set({compiler/rustc_ast_pretty}) - Set({compiler/rustc_attr_ir}) - Set({compiler/rustc_attr_parsing}) - - Set({compiler/rustc_baked_icu_data}) - Set({compiler/rustc_borrowck}) - Set({compiler/rustc_builtin_macros}) - Set({compiler/rustc_codegen_llvm}) diff --git a/src/bootstrap/src/core/builder/cli_paths/snapshots/x_check.snap b/src/bootstrap/src/core/builder/cli_paths/snapshots/x_check.snap index 8f9abbf0e3f5a..eb848cb57e67f 100644 --- a/src/bootstrap/src/core/builder/cli_paths/snapshots/x_check.snap +++ b/src/bootstrap/src/core/builder/cli_paths/snapshots/x_check.snap @@ -15,7 +15,6 @@ expression: check - Set({compiler/rustc_ast_pretty}) - Set({compiler/rustc_attr_ir}) - Set({compiler/rustc_attr_parsing}) - - Set({compiler/rustc_baked_icu_data}) - Set({compiler/rustc_borrowck}) - Set({compiler/rustc_builtin_macros}) - Set({compiler/rustc_codegen_llvm}) diff --git a/src/bootstrap/src/core/builder/cli_paths/snapshots/x_check_compiler.snap b/src/bootstrap/src/core/builder/cli_paths/snapshots/x_check_compiler.snap index efedf514001c2..ac338441af824 100644 --- a/src/bootstrap/src/core/builder/cli_paths/snapshots/x_check_compiler.snap +++ b/src/bootstrap/src/core/builder/cli_paths/snapshots/x_check_compiler.snap @@ -15,7 +15,6 @@ expression: check compiler - Set({compiler/rustc_ast_pretty}) - Set({compiler/rustc_attr_ir}) - Set({compiler/rustc_attr_parsing}) - - Set({compiler/rustc_baked_icu_data}) - Set({compiler/rustc_borrowck}) - Set({compiler/rustc_builtin_macros}) - Set({compiler/rustc_codegen_llvm}) diff --git a/src/bootstrap/src/core/builder/cli_paths/snapshots/x_check_compiletest_include_default_paths.snap b/src/bootstrap/src/core/builder/cli_paths/snapshots/x_check_compiletest_include_default_paths.snap index 526aa31cc74af..8d0ec95e02658 100644 --- a/src/bootstrap/src/core/builder/cli_paths/snapshots/x_check_compiletest_include_default_paths.snap +++ b/src/bootstrap/src/core/builder/cli_paths/snapshots/x_check_compiletest_include_default_paths.snap @@ -15,7 +15,6 @@ expression: check compiletest --include-default-paths - Set({compiler/rustc_ast_pretty}) - Set({compiler/rustc_attr_ir}) - Set({compiler/rustc_attr_parsing}) - - Set({compiler/rustc_baked_icu_data}) - Set({compiler/rustc_borrowck}) - Set({compiler/rustc_builtin_macros}) - Set({compiler/rustc_codegen_llvm}) diff --git a/src/bootstrap/src/core/builder/cli_paths/snapshots/x_clippy.snap b/src/bootstrap/src/core/builder/cli_paths/snapshots/x_clippy.snap index 17b69d85ff821..de6fde4a754e8 100644 --- a/src/bootstrap/src/core/builder/cli_paths/snapshots/x_clippy.snap +++ b/src/bootstrap/src/core/builder/cli_paths/snapshots/x_clippy.snap @@ -30,7 +30,6 @@ expression: clippy - Set({compiler/rustc_ast_pretty}) - Set({compiler/rustc_attr_ir}) - Set({compiler/rustc_attr_parsing}) - - Set({compiler/rustc_baked_icu_data}) - Set({compiler/rustc_borrowck}) - Set({compiler/rustc_builtin_macros}) - Set({compiler/rustc_codegen_llvm}) diff --git a/src/bootstrap/src/core/builder/cli_paths/snapshots/x_fix.snap b/src/bootstrap/src/core/builder/cli_paths/snapshots/x_fix.snap index 01f0ef3f05d67..e8a77106c8c97 100644 --- a/src/bootstrap/src/core/builder/cli_paths/snapshots/x_fix.snap +++ b/src/bootstrap/src/core/builder/cli_paths/snapshots/x_fix.snap @@ -15,7 +15,6 @@ expression: fix - Set({compiler/rustc_ast_pretty}) - Set({compiler/rustc_attr_ir}) - Set({compiler/rustc_attr_parsing}) - - Set({compiler/rustc_baked_icu_data}) - Set({compiler/rustc_borrowck}) - Set({compiler/rustc_builtin_macros}) - Set({compiler/rustc_codegen_llvm}) diff --git a/src/bootstrap/src/core/builder/cli_paths/snapshots/x_test.snap b/src/bootstrap/src/core/builder/cli_paths/snapshots/x_test.snap index 1fe97ca766c81..44bf24b81413d 100644 --- a/src/bootstrap/src/core/builder/cli_paths/snapshots/x_test.snap +++ b/src/bootstrap/src/core/builder/cli_paths/snapshots/x_test.snap @@ -82,7 +82,6 @@ expression: test - Set({compiler/rustc_ast_pretty}) - Set({compiler/rustc_attr_ir}) - Set({compiler/rustc_attr_parsing}) - - Set({compiler/rustc_baked_icu_data}) - Set({compiler/rustc_borrowck}) - Set({compiler/rustc_builtin_macros}) - Set({compiler/rustc_codegen_llvm}) diff --git a/src/bootstrap/src/core/builder/cli_paths/snapshots/x_test_skip_coverage.snap b/src/bootstrap/src/core/builder/cli_paths/snapshots/x_test_skip_coverage.snap index f112cdafa81b3..0ba7dd237a62d 100644 --- a/src/bootstrap/src/core/builder/cli_paths/snapshots/x_test_skip_coverage.snap +++ b/src/bootstrap/src/core/builder/cli_paths/snapshots/x_test_skip_coverage.snap @@ -79,7 +79,6 @@ expression: test --skip=coverage - Set({compiler/rustc_ast_pretty}) - Set({compiler/rustc_attr_ir}) - Set({compiler/rustc_attr_parsing}) - - Set({compiler/rustc_baked_icu_data}) - Set({compiler/rustc_borrowck}) - Set({compiler/rustc_builtin_macros}) - Set({compiler/rustc_codegen_llvm}) diff --git a/src/bootstrap/src/core/builder/cli_paths/snapshots/x_test_skip_coverage_map.snap b/src/bootstrap/src/core/builder/cli_paths/snapshots/x_test_skip_coverage_map.snap index 401cdc8432d2f..c73a049573052 100644 --- a/src/bootstrap/src/core/builder/cli_paths/snapshots/x_test_skip_coverage_map.snap +++ b/src/bootstrap/src/core/builder/cli_paths/snapshots/x_test_skip_coverage_map.snap @@ -82,7 +82,6 @@ expression: test --skip=coverage-map - Set({compiler/rustc_ast_pretty}) - Set({compiler/rustc_attr_ir}) - Set({compiler/rustc_attr_parsing}) - - Set({compiler/rustc_baked_icu_data}) - Set({compiler/rustc_borrowck}) - Set({compiler/rustc_builtin_macros}) - Set({compiler/rustc_codegen_llvm}) diff --git a/src/bootstrap/src/core/builder/cli_paths/snapshots/x_test_skip_coverage_run.snap b/src/bootstrap/src/core/builder/cli_paths/snapshots/x_test_skip_coverage_run.snap index 01d5b362e928f..cfdf14a738906 100644 --- a/src/bootstrap/src/core/builder/cli_paths/snapshots/x_test_skip_coverage_run.snap +++ b/src/bootstrap/src/core/builder/cli_paths/snapshots/x_test_skip_coverage_run.snap @@ -82,7 +82,6 @@ expression: test --skip=coverage-run - Set({compiler/rustc_ast_pretty}) - Set({compiler/rustc_attr_ir}) - Set({compiler/rustc_attr_parsing}) - - Set({compiler/rustc_baked_icu_data}) - Set({compiler/rustc_borrowck}) - Set({compiler/rustc_builtin_macros}) - Set({compiler/rustc_codegen_llvm}) diff --git a/src/bootstrap/src/core/builder/cli_paths/snapshots/x_test_skip_tests.snap b/src/bootstrap/src/core/builder/cli_paths/snapshots/x_test_skip_tests.snap index b936eeefe8805..d21d4613add25 100644 --- a/src/bootstrap/src/core/builder/cli_paths/snapshots/x_test_skip_tests.snap +++ b/src/bootstrap/src/core/builder/cli_paths/snapshots/x_test_skip_tests.snap @@ -40,7 +40,6 @@ expression: test --skip=tests - Set({compiler/rustc_ast_pretty}) - Set({compiler/rustc_attr_ir}) - Set({compiler/rustc_attr_parsing}) - - Set({compiler/rustc_baked_icu_data}) - Set({compiler/rustc_borrowck}) - Set({compiler/rustc_builtin_macros}) - Set({compiler/rustc_codegen_llvm}) diff --git a/src/bootstrap/src/core/builder/cli_paths/snapshots/x_test_skip_tests_coverage.snap b/src/bootstrap/src/core/builder/cli_paths/snapshots/x_test_skip_tests_coverage.snap index c7ea1c663a030..68853acdba170 100644 --- a/src/bootstrap/src/core/builder/cli_paths/snapshots/x_test_skip_tests_coverage.snap +++ b/src/bootstrap/src/core/builder/cli_paths/snapshots/x_test_skip_tests_coverage.snap @@ -79,7 +79,6 @@ expression: test --skip=tests/coverage - Set({compiler/rustc_ast_pretty}) - Set({compiler/rustc_attr_ir}) - Set({compiler/rustc_attr_parsing}) - - Set({compiler/rustc_baked_icu_data}) - Set({compiler/rustc_borrowck}) - Set({compiler/rustc_builtin_macros}) - Set({compiler/rustc_codegen_llvm}) diff --git a/src/bootstrap/src/core/builder/cli_paths/snapshots/x_test_skip_tests_etc.snap b/src/bootstrap/src/core/builder/cli_paths/snapshots/x_test_skip_tests_etc.snap index 98b39e619fad8..6a24274b01835 100644 --- a/src/bootstrap/src/core/builder/cli_paths/snapshots/x_test_skip_tests_etc.snap +++ b/src/bootstrap/src/core/builder/cli_paths/snapshots/x_test_skip_tests_etc.snap @@ -24,7 +24,6 @@ expression: test --skip=tests --skip=library --skip=tidyselftest - Set({compiler/rustc_ast_pretty}) - Set({compiler/rustc_attr_ir}) - Set({compiler/rustc_attr_parsing}) - - Set({compiler/rustc_baked_icu_data}) - Set({compiler/rustc_borrowck}) - Set({compiler/rustc_builtin_macros}) - Set({compiler/rustc_codegen_llvm}) diff --git a/src/bootstrap/src/core/builder/tests.rs b/src/bootstrap/src/core/builder/tests.rs index 544c47602136a..92cd34fb72b73 100644 --- a/src/bootstrap/src/core/builder/tests.rs +++ b/src/bootstrap/src/core/builder/tests.rs @@ -1492,7 +1492,7 @@ mod snapshot { #[test] fn check_compiler_no_explicit_stage() { let ctx = TestCtx::new(); - expect_test::expect![["[check] rustc 0 -> rustc 1 (78 crates)"]] + expect_test::expect!["[check] rustc 0 -> rustc 1 (77 crates)"] .assert_eq(&ctx.config("check").path("compiler").render_steps()); } @@ -1513,7 +1513,7 @@ mod snapshot { #[test] fn check_compiler_stage_1() { let ctx = TestCtx::new(); - expect_test::expect![["[check] rustc 0 -> rustc 1 (78 crates)"]] + expect_test::expect!["[check] rustc 0 -> rustc 1 (77 crates)"] .assert_eq(&ctx.config("check").path("compiler").stage(1).render_steps()); } @@ -1524,7 +1524,7 @@ mod snapshot { [build] llvm [build] rustc 0 -> rustc 1 [build] rustc 1 -> std 1 - [check] rustc 1 -> rustc 2 (78 crates)"#]] + [check] rustc 1 -> rustc 2 (77 crates)"#]] .assert_eq(&ctx.config("check").path("compiler").stage(2).render_steps()); } @@ -1536,7 +1536,7 @@ mod snapshot { [build] rustc 0 -> rustc 1 [build] rustc 1 -> std 1 [check] rustc 1 -> std 1 - [check] rustc 1 -> rustc 2 (78 crates) + [check] rustc 1 -> rustc 2 (77 crates) [check] rustc 1 -> rustc 2 [check] rustc 1 -> Rustdoc 2 [check] rustc 1 -> rustc_codegen_cranelift 2 @@ -1617,7 +1617,7 @@ mod snapshot { expect_test::expect![[""]] .assert_eq(&ctx.config("check").paths(&["library"]).args(&args).render_steps()); - expect_test::expect![["[check] rustc 0 -> rustc 1 (78 crates)"]].assert_eq( + expect_test::expect!["[check] rustc 0 -> rustc 1 (77 crates)"].assert_eq( &ctx.config("check").paths(&["library", "compiler"]).args(&args).render_steps(), ); } @@ -2750,7 +2750,7 @@ mod snapshot { #[test] fn fix_compiler() { let ctx = TestCtx::new(); - expect_test::expect![["[fix] rustc 0 -> rustc 1 (78 crates)"]] + expect_test::expect!["[fix] rustc 0 -> rustc 1 (77 crates)"] .assert_eq(&ctx.config("fix").path("compiler").render_steps()); } } diff --git a/src/doc/rustc/src/platform-support/powerpc64-unknown-linux-gnuelfv2.md b/src/doc/rustc/src/platform-support/powerpc64-unknown-linux-gnuelfv2.md index 7ab29b394fcdd..de7b7cb414f3f 100644 --- a/src/doc/rustc/src/platform-support/powerpc64-unknown-linux-gnuelfv2.md +++ b/src/doc/rustc/src/platform-support/powerpc64-unknown-linux-gnuelfv2.md @@ -11,6 +11,7 @@ the oldest IBM server CPU supported is therefore POWER6. ## Target maintainers [@Gelbpunkt](https://github.com/Gelbpunkt) +[@amaanq](https://github.com/amaanq) ## Requirements diff --git a/src/librustdoc/json/conversions.rs b/src/librustdoc/json/conversions.rs index 88e6d48e975c3..cd487de995cba 100644 --- a/src/librustdoc/json/conversions.rs +++ b/src/librustdoc/json/conversions.rs @@ -1062,7 +1062,7 @@ fn maybe_from_hir_attr( let kind = match attr { rustc_attr_ir::Attribute::Parsed(kind) => kind, - rustc_attr_ir::Attribute::Tool(_) | rustc_attr_ir::Attribute::DeriveHelper(_) => { + rustc_attr_ir::Attribute::Tool { .. } | rustc_attr_ir::Attribute::DeriveHelper(_) => { // FIXME: We should handle `#[doc(hidden)]`. return vec![other_attr(tcx, attr)]; } diff --git a/src/tools/clippy/clippy_lints_internal/src/almost_standard_lint_formulation.rs b/src/tools/clippy/clippy_lints_internal/src/almost_standard_lint_formulation.rs index 07280b96e800a..35ec2fe51c4fb 100644 --- a/src/tools/clippy/clippy_lints_internal/src/almost_standard_lint_formulation.rs +++ b/src/tools/clippy/clippy_lints_internal/src/almost_standard_lint_formulation.rs @@ -20,7 +20,7 @@ declare_tool_lint! { pub clippy::ALMOST_STANDARD_LINT_FORMULATION, Warn, "lint formulations must have a standardized format.", - report_in_external_macro: true + @report_in_external_macro = true } impl_lint_pass!(AlmostStandardFormulation => [ALMOST_STANDARD_LINT_FORMULATION]); diff --git a/src/tools/clippy/clippy_lints_internal/src/collapsible_span_lint_calls.rs b/src/tools/clippy/clippy_lints_internal/src/collapsible_span_lint_calls.rs index 0cd10da70a0b5..0705dd0ff576e 100644 --- a/src/tools/clippy/clippy_lints_internal/src/collapsible_span_lint_calls.rs +++ b/src/tools/clippy/clippy_lints_internal/src/collapsible_span_lint_calls.rs @@ -68,7 +68,7 @@ declare_tool_lint! { pub clippy::COLLAPSIBLE_SPAN_LINT_CALLS, Warn, "found collapsible `span_lint_and_then` calls", - report_in_external_macro: true + @report_in_external_macro = true } declare_lint_pass!(CollapsibleCalls => [COLLAPSIBLE_SPAN_LINT_CALLS]); diff --git a/src/tools/clippy/clippy_lints_internal/src/lint_without_lint_pass.rs b/src/tools/clippy/clippy_lints_internal/src/lint_without_lint_pass.rs index 408e5914f3ef6..6afdb5f8bd2e1 100644 --- a/src/tools/clippy/clippy_lints_internal/src/lint_without_lint_pass.rs +++ b/src/tools/clippy/clippy_lints_internal/src/lint_without_lint_pass.rs @@ -39,7 +39,7 @@ declare_tool_lint! { pub clippy::LINT_WITHOUT_LINT_PASS, Warn, "declaring a lint without associating it in a LintPass", - report_in_external_macro: true + @report_in_external_macro = true } @@ -63,7 +63,7 @@ declare_tool_lint! { pub clippy::DEFAULT_LINT, Warn, "found 'default lint description' in a lint declaration", - report_in_external_macro: true + @report_in_external_macro = true } declare_tool_lint! { @@ -76,7 +76,7 @@ declare_tool_lint! { pub clippy::INVALID_CLIPPY_VERSION_ATTRIBUTE, Warn, "found an invalid `clippy::version` attribute", - report_in_external_macro: true + @report_in_external_macro = true } declare_tool_lint! { @@ -85,7 +85,7 @@ declare_tool_lint! { pub clippy::MISSING_CLIPPY_VERSION_ATTRIBUTE, Warn, "found clippy lint without `clippy::version` attribute", - report_in_external_macro: true + @report_in_external_macro = true } #[derive(Clone, Debug, Default)] diff --git a/src/tools/clippy/clippy_lints_internal/src/msrv_attr_impl.rs b/src/tools/clippy/clippy_lints_internal/src/msrv_attr_impl.rs index 1c0cf79b4c485..f40b048b5f80a 100644 --- a/src/tools/clippy/clippy_lints_internal/src/msrv_attr_impl.rs +++ b/src/tools/clippy/clippy_lints_internal/src/msrv_attr_impl.rs @@ -13,7 +13,7 @@ declare_tool_lint! { pub clippy::MISSING_MSRV_ATTR_IMPL, Warn, "checking if all necessary steps were taken when adding a MSRV to a lint", - report_in_external_macro: true + @report_in_external_macro = true } declare_lint_pass!(MsrvAttrImpl => [MISSING_MSRV_ATTR_IMPL]); diff --git a/src/tools/clippy/clippy_lints_internal/src/outer_expn_data_pass.rs b/src/tools/clippy/clippy_lints_internal/src/outer_expn_data_pass.rs index a53c9b12e41e4..ed087d2b16c0f 100644 --- a/src/tools/clippy/clippy_lints_internal/src/outer_expn_data_pass.rs +++ b/src/tools/clippy/clippy_lints_internal/src/outer_expn_data_pass.rs @@ -25,7 +25,7 @@ declare_tool_lint! { pub clippy::OUTER_EXPN_EXPN_DATA, Warn, "using `cx.outer_expn().expn_data()` instead of `cx.outer_expn_data()`", - report_in_external_macro: true + @report_in_external_macro = true } declare_lint_pass!(OuterExpnDataPass => [OUTER_EXPN_EXPN_DATA]); diff --git a/src/tools/clippy/clippy_lints_internal/src/symbols.rs b/src/tools/clippy/clippy_lints_internal/src/symbols.rs index 99be873863a17..206c101eb46a7 100644 --- a/src/tools/clippy/clippy_lints_internal/src/symbols.rs +++ b/src/tools/clippy/clippy_lints_internal/src/symbols.rs @@ -30,7 +30,7 @@ declare_tool_lint! { pub clippy::INTERNING_LITERALS, Warn, "interning a symbol that is a literal", - report_in_external_macro: true + @report_in_external_macro = true } declare_tool_lint! { @@ -52,7 +52,7 @@ declare_tool_lint! { pub clippy::SYMBOL_AS_STR, Warn, "calls to `Symbol::as_str`", - report_in_external_macro: true + @report_in_external_macro = true } #[derive(Default)] diff --git a/src/tools/clippy/clippy_lints_internal/src/unnecessary_def_path.rs b/src/tools/clippy/clippy_lints_internal/src/unnecessary_def_path.rs index 7cac000447ec5..5d2b8aaac446b 100644 --- a/src/tools/clippy/clippy_lints_internal/src/unnecessary_def_path.rs +++ b/src/tools/clippy/clippy_lints_internal/src/unnecessary_def_path.rs @@ -31,7 +31,7 @@ declare_tool_lint! { pub clippy::UNNECESSARY_DEF_PATH, Warn, "using a def path when a diagnostic item or a `LangItem` is available", - report_in_external_macro: true + @report_in_external_macro = true } declare_lint_pass!(UnnecessaryDefPath => [UNNECESSARY_DEF_PATH]); diff --git a/src/tools/clippy/clippy_lints_internal/src/unsorted_clippy_utils_paths.rs b/src/tools/clippy/clippy_lints_internal/src/unsorted_clippy_utils_paths.rs index badb106bd8c3c..9263695ad35ab 100644 --- a/src/tools/clippy/clippy_lints_internal/src/unsorted_clippy_utils_paths.rs +++ b/src/tools/clippy/clippy_lints_internal/src/unsorted_clippy_utils_paths.rs @@ -15,7 +15,7 @@ declare_tool_lint! { pub clippy::UNSORTED_CLIPPY_UTILS_PATHS, Warn, "various things that will negatively affect your clippy experience", - report_in_external_macro: true + @report_in_external_macro = true } declare_lint_pass!(UnsortedClippyUtilsPaths => [UNSORTED_CLIPPY_UTILS_PATHS]); diff --git a/src/tools/clippy/clippy_lints_internal/src/unusual_names.rs b/src/tools/clippy/clippy_lints_internal/src/unusual_names.rs index f7a5b1e591030..2dade16817c73 100644 --- a/src/tools/clippy/clippy_lints_internal/src/unusual_names.rs +++ b/src/tools/clippy/clippy_lints_internal/src/unusual_names.rs @@ -27,7 +27,7 @@ declare_tool_lint! { pub clippy::UNUSUAL_NAMES, Warn, "commonly used concepts should use usual same variable name.", - report_in_external_macro: true + @report_in_external_macro = true } declare_lint_pass!(UnusualNames => [UNUSUAL_NAMES]); diff --git a/src/tools/clippy/clippy_utils/src/attrs.rs b/src/tools/clippy/clippy_utils/src/attrs.rs index be9d6761f3625..a6be150464d3e 100644 --- a/src/tools/clippy/clippy_utils/src/attrs.rs +++ b/src/tools/clippy/clippy_utils/src/attrs.rs @@ -168,10 +168,10 @@ impl LimitStack { fn parse_attrs(sess: &Session, attrs: &[rustc_attr_ir::Attribute], name: Symbol, mut f: F) { let attrs = attrs.iter().filter_map(move |attr| { - if let rustc_attr_ir::Attribute::Tool(t) = attr - && *t.path.segments == [sym::clippy, name] + if let rustc_attr_ir::Attribute::Tool { item, .. } = attr + && *item.path.segments == [sym::clippy, name] { - Some(&**t) + Some(&**item) } else { None } diff --git a/src/tools/clippy/clippy_utils/src/msrvs.rs b/src/tools/clippy/clippy_utils/src/msrvs.rs index 43f88863c8bde..dbc239bc094a0 100644 --- a/src/tools/clippy/clippy_utils/src/msrvs.rs +++ b/src/tools/clippy/clippy_utils/src/msrvs.rs @@ -272,7 +272,7 @@ fn parse_ast_attrs(attrs: &[Attribute]) -> Option { fn parse_hir_attrs(attrs: &[rustc_attr_ir::Attribute]) -> Option { let msrv = attrs.iter().find_map(|attr| { - if let rustc_attr_ir::Attribute::Tool(item) = attr + if let rustc_attr_ir::Attribute::Tool { item, .. } = attr && let [sym::clippy, sym::msrv] = item.path.segments { attr.value_lit().and_then(rustc_ast::MetaItemLit::value_as_str) diff --git a/src/tools/clippy/declare_clippy_lint/src/lib.rs b/src/tools/clippy/declare_clippy_lint/src/lib.rs index 7d2efa95366c2..cb87e651e8e0b 100644 --- a/src/tools/clippy/declare_clippy_lint/src/lib.rs +++ b/src/tools/clippy/declare_clippy_lint/src/lib.rs @@ -134,7 +134,7 @@ macro_rules! declare_clippy_lint_inner { $vis clippy::$lint_name, $level, $desc, - report_in_external_macro:true + @report_in_external_macro = true $(, @eval_always = $eval_always)? } diff --git a/src/tools/clippy/tests/ui-internal/check_clippy_version_attribute.rs b/src/tools/clippy/tests/ui-internal/check_clippy_version_attribute.rs index 6bb2d68afdc17..6bd6ed5e60473 100644 --- a/src/tools/clippy/tests/ui-internal/check_clippy_version_attribute.rs +++ b/src/tools/clippy/tests/ui-internal/check_clippy_version_attribute.rs @@ -15,7 +15,7 @@ declare_tool_lint! { pub clippy::VALID_ONE, Warn, "One", - report_in_external_macro: true + @report_in_external_macro = true } declare_tool_lint! { @@ -23,7 +23,7 @@ declare_tool_lint! { pub clippy::VALID_TWO, Warn, "Two", - report_in_external_macro: true + @report_in_external_macro = true } declare_tool_lint! { @@ -31,7 +31,7 @@ declare_tool_lint! { pub clippy::VALID_THREE, Warn, "Three", - report_in_external_macro: true + @report_in_external_macro = true } /////////////////////// @@ -43,7 +43,7 @@ declare_tool_lint! { pub clippy::INVALID_ONE, Warn, "One", - report_in_external_macro: true + @report_in_external_macro = true } declare_tool_lint! { @@ -52,7 +52,7 @@ declare_tool_lint! { pub clippy::INVALID_TWO, Warn, "Two", - report_in_external_macro: true + @report_in_external_macro = true } /////////////////////// @@ -64,7 +64,7 @@ declare_tool_lint! { pub clippy::MISSING_ATTRIBUTE_ONE, Warn, "Two", - report_in_external_macro: true + @report_in_external_macro = true } declare_tool_lint! { @@ -72,7 +72,7 @@ declare_tool_lint! { pub clippy::MISSING_ATTRIBUTE_TWO, Warn, "Two", - report_in_external_macro: true + @report_in_external_macro = true } #[allow(clippy::missing_clippy_version_attribute)] @@ -81,7 +81,7 @@ mod internal_clippy_lints { pub clippy::ALLOW_MISSING_ATTRIBUTE_ONE, Warn, "Two", - report_in_external_macro: true + @report_in_external_macro = true } } diff --git a/src/tools/clippy/tests/ui-internal/check_clippy_version_attribute.stderr b/src/tools/clippy/tests/ui-internal/check_clippy_version_attribute.stderr index de510255ed5d7..ee37c598b45a4 100644 --- a/src/tools/clippy/tests/ui-internal/check_clippy_version_attribute.stderr +++ b/src/tools/clippy/tests/ui-internal/check_clippy_version_attribute.stderr @@ -6,7 +6,7 @@ LL | | LL | | #[clippy::version = "1.2.3.4.5.6"] LL | | pub clippy::INVALID_ONE, ... | -LL | | report_in_external_macro: true +LL | | @report_in_external_macro = true LL | | } | |_^ | @@ -26,7 +26,7 @@ LL | | LL | | #[clippy::version = "I'm a string"] LL | | pub clippy::INVALID_TWO, ... | -LL | | report_in_external_macro: true +LL | | @report_in_external_macro = true LL | | } | |_^ | @@ -41,7 +41,7 @@ LL | | LL | | #[clippy::version] LL | | pub clippy::MISSING_ATTRIBUTE_ONE, ... | -LL | | report_in_external_macro: true +LL | | @report_in_external_macro = true LL | | } | |_^ | @@ -61,7 +61,7 @@ LL | | LL | | pub clippy::MISSING_ATTRIBUTE_TWO, LL | | Warn, LL | | "Two", -LL | | report_in_external_macro: true +LL | | @report_in_external_macro = true LL | | } | |_^ | diff --git a/src/tools/clippy/tests/ui-internal/check_formulation.rs b/src/tools/clippy/tests/ui-internal/check_formulation.rs index 54f17dd083eb5..392c7e51141eb 100644 --- a/src/tools/clippy/tests/ui-internal/check_formulation.rs +++ b/src/tools/clippy/tests/ui-internal/check_formulation.rs @@ -16,7 +16,7 @@ declare_tool_lint! { pub clippy::VALID, Warn, "One", - report_in_external_macro: true + @report_in_external_macro = true } declare_tool_lint! { @@ -27,7 +27,7 @@ declare_tool_lint! { pub clippy::INVALID1, Warn, "One", - report_in_external_macro: true + @report_in_external_macro = true } declare_tool_lint! { @@ -38,7 +38,7 @@ declare_tool_lint! { pub clippy::INVALID2, Warn, "One", - report_in_external_macro: true + @report_in_external_macro = true } declare_tool_lint! { @@ -49,7 +49,7 @@ declare_tool_lint! { pub clippy::ALLOWED_INVALID, Warn, "One", - report_in_external_macro: true + @report_in_external_macro = true } declare_lint_pass!(Pass => [VALID, INVALID1, INVALID2]); diff --git a/src/tools/clippy/tests/ui-internal/collapsible_span_lint_calls.fixed b/src/tools/clippy/tests/ui-internal/collapsible_span_lint_calls.fixed index 9468681480e16..4944b6baa4bd5 100644 --- a/src/tools/clippy/tests/ui-internal/collapsible_span_lint_calls.fixed +++ b/src/tools/clippy/tests/ui-internal/collapsible_span_lint_calls.fixed @@ -18,7 +18,7 @@ declare_tool_lint! { pub clippy::TEST_LINT, Warn, "", - report_in_external_macro: true + @report_in_external_macro = true } declare_lint_pass!(Pass => [TEST_LINT]); diff --git a/src/tools/clippy/tests/ui-internal/collapsible_span_lint_calls.rs b/src/tools/clippy/tests/ui-internal/collapsible_span_lint_calls.rs index 8a993b4f6d67f..2bec2eaec9aa0 100644 --- a/src/tools/clippy/tests/ui-internal/collapsible_span_lint_calls.rs +++ b/src/tools/clippy/tests/ui-internal/collapsible_span_lint_calls.rs @@ -18,7 +18,7 @@ declare_tool_lint! { pub clippy::TEST_LINT, Warn, "", - report_in_external_macro: true + @report_in_external_macro = true } declare_lint_pass!(Pass => [TEST_LINT]); diff --git a/src/tools/clippy/tests/ui-internal/default_lint.rs b/src/tools/clippy/tests/ui-internal/default_lint.rs index 79ddb5051df57..2a60ee487ba71 100644 --- a/src/tools/clippy/tests/ui-internal/default_lint.rs +++ b/src/tools/clippy/tests/ui-internal/default_lint.rs @@ -12,7 +12,7 @@ declare_tool_lint! { pub clippy::TEST_LINT, Warn, "", - report_in_external_macro: true + @report_in_external_macro = true } declare_tool_lint! { @@ -20,7 +20,7 @@ declare_tool_lint! { pub clippy::TEST_LINT_DEFAULT, Warn, "default lint description", - report_in_external_macro: true + @report_in_external_macro = true } declare_lint_pass!(Pass => [TEST_LINT]); diff --git a/src/tools/clippy/tests/ui-internal/default_lint.stderr b/src/tools/clippy/tests/ui-internal/default_lint.stderr index 2c700ec82dcd4..a1787cbd272c7 100644 --- a/src/tools/clippy/tests/ui-internal/default_lint.stderr +++ b/src/tools/clippy/tests/ui-internal/default_lint.stderr @@ -6,7 +6,7 @@ LL | | LL | | pub clippy::TEST_LINT_DEFAULT, LL | | Warn, LL | | "default lint description", -LL | | report_in_external_macro: true +LL | | @report_in_external_macro = true LL | | } | |_^ | diff --git a/src/tools/clippy/tests/ui-internal/lint_without_lint_pass.rs b/src/tools/clippy/tests/ui-internal/lint_without_lint_pass.rs index 71e32fe23fe6a..ad1f3a8fe03a6 100644 --- a/src/tools/clippy/tests/ui-internal/lint_without_lint_pass.rs +++ b/src/tools/clippy/tests/ui-internal/lint_without_lint_pass.rs @@ -14,21 +14,21 @@ declare_tool_lint! { pub clippy::TEST_LINT, Warn, "", - report_in_external_macro: true + @report_in_external_macro = true } declare_tool_lint! { pub clippy::TEST_LINT_REGISTERED, Warn, "", - report_in_external_macro: true + @report_in_external_macro = true } declare_tool_lint! { pub clippy::TEST_LINT_REGISTERED_ONLY_IMPL, Warn, "", - report_in_external_macro: true + @report_in_external_macro = true } pub struct Pass; diff --git a/src/tools/clippy/tests/ui-internal/lint_without_lint_pass.stderr b/src/tools/clippy/tests/ui-internal/lint_without_lint_pass.stderr index 3798293f4c111..18123985d4658 100644 --- a/src/tools/clippy/tests/ui-internal/lint_without_lint_pass.stderr +++ b/src/tools/clippy/tests/ui-internal/lint_without_lint_pass.stderr @@ -6,7 +6,7 @@ LL | | LL | | pub clippy::TEST_LINT, LL | | Warn, LL | | "", -LL | | report_in_external_macro: true +LL | | @report_in_external_macro = true LL | | } | |_^ | diff --git a/src/tools/clippy/tests/ui/large_types_passed_by_value.rs b/src/tools/clippy/tests/ui/large_types_passed_by_value.rs index 562a46306e065..50148ff9b6a70 100644 --- a/src/tools/clippy/tests/ui/large_types_passed_by_value.rs +++ b/src/tools/clippy/tests/ui/large_types_passed_by_value.rs @@ -71,4 +71,14 @@ fn foo(x: LargeAndCopy) { todo!(); } +#[derive(Clone, Copy)] +struct Big([u64; 1024]); + +trait Trait { + fn named(x: Big); + //~^ large_types_passed_by_value + fn unnamed(_: Big); + //~^ large_types_passed_by_value +} + fn main() {} diff --git a/src/tools/clippy/tests/ui/large_types_passed_by_value.stderr b/src/tools/clippy/tests/ui/large_types_passed_by_value.stderr index 0ad68bc326e02..ab0d9cae5b440 100644 --- a/src/tools/clippy/tests/ui/large_types_passed_by_value.stderr +++ b/src/tools/clippy/tests/ui/large_types_passed_by_value.stderr @@ -49,5 +49,17 @@ error: this argument (N byte) is passed by value, but might be more efficient if LL | fn foo(x: LargeAndCopy) { | ^^^^^^^^^^^^ help: consider passing by reference instead: `&LargeAndCopy` -error: aborting due to 8 previous errors +error: this argument (N byte) is passed by value, but might be more efficient if passed by reference (limit: N byte) + --> tests/ui/large_types_passed_by_value.rs:78:17 + | +LL | fn named(x: Big); + | ^^^ help: consider passing by reference instead: `&Big` + +error: this argument (N byte) is passed by value, but might be more efficient if passed by reference (limit: N byte) + --> tests/ui/large_types_passed_by_value.rs:80:19 + | +LL | fn unnamed(_: Big); + | ^^^ help: consider passing by reference instead: `&Big` + +error: aborting due to 10 previous errors diff --git a/src/tools/clippy/tests/ui/shadow.rs b/src/tools/clippy/tests/ui/shadow.rs index 90953cda10107..0235671e67905 100644 --- a/src/tools/clippy/tests/ui/shadow.rs +++ b/src/tools/clippy/tests/ui/shadow.rs @@ -177,4 +177,19 @@ fn issue14377() { S { c, d } = S { c: 1, d: 2 }; } +fn plain_same(x: u8) { let x = x; } +//~^ shadow_same +fn tuple_same((x,): (u8,)) { let x = x; } +//~^ shadow_same + +fn plain_reuse(x: u8) { let x = x + 1; } +//~^ shadow_reuse +fn tuple_reuse((x,): (u8,)) { let x = x + 1; } +//~^ shadow_reuse + +fn plain_unrelated(x: u8) { let x = 1u8; } +//~^ shadow_unrelated +fn tuple_unrelated((x,): (u8,)) { let x = 1u8; } +//~^ shadow_unrelated + fn main() {} diff --git a/src/tools/clippy/tests/ui/shadow.stderr b/src/tools/clippy/tests/ui/shadow.stderr index c356e4a130d06..ef94faa1a30aa 100644 --- a/src/tools/clippy/tests/ui/shadow.stderr +++ b/src/tools/clippy/tests/ui/shadow.stderr @@ -316,5 +316,77 @@ note: previous binding is here LL | fn issue13795(value: Issue13795) { | ^^^^^ -error: aborting due to 26 previous errors +error: `x` is shadowed by itself in `x` + --> tests/ui/shadow.rs:180:28 + | +LL | fn plain_same(x: u8) { let x = x; } + | ^ + | +note: previous binding is here + --> tests/ui/shadow.rs:180:15 + | +LL | fn plain_same(x: u8) { let x = x; } + | ^ + +error: `x` is shadowed by itself in `x` + --> tests/ui/shadow.rs:182:34 + | +LL | fn tuple_same((x,): (u8,)) { let x = x; } + | ^ + | +note: previous binding is here + --> tests/ui/shadow.rs:182:16 + | +LL | fn tuple_same((x,): (u8,)) { let x = x; } + | ^ + +error: `x` is shadowed + --> tests/ui/shadow.rs:185:29 + | +LL | fn plain_reuse(x: u8) { let x = x + 1; } + | ^ + | +note: previous binding is here + --> tests/ui/shadow.rs:185:16 + | +LL | fn plain_reuse(x: u8) { let x = x + 1; } + | ^ + +error: `x` is shadowed + --> tests/ui/shadow.rs:187:35 + | +LL | fn tuple_reuse((x,): (u8,)) { let x = x + 1; } + | ^ + | +note: previous binding is here + --> tests/ui/shadow.rs:187:17 + | +LL | fn tuple_reuse((x,): (u8,)) { let x = x + 1; } + | ^ + +error: `x` shadows a previous, unrelated binding + --> tests/ui/shadow.rs:190:33 + | +LL | fn plain_unrelated(x: u8) { let x = 1u8; } + | ^ + | +note: previous binding is here + --> tests/ui/shadow.rs:190:20 + | +LL | fn plain_unrelated(x: u8) { let x = 1u8; } + | ^ + +error: `x` shadows a previous, unrelated binding + --> tests/ui/shadow.rs:192:39 + | +LL | fn tuple_unrelated((x,): (u8,)) { let x = 1u8; } + | ^ + | +note: previous binding is here + --> tests/ui/shadow.rs:192:21 + | +LL | fn tuple_unrelated((x,): (u8,)) { let x = 1u8; } + | ^ + +error: aborting due to 32 previous errors diff --git a/src/tools/tidy/src/deps.rs b/src/tools/tidy/src/deps.rs index cc0443410ecd7..db21b6e43dedf 100644 --- a/src/tools/tidy/src/deps.rs +++ b/src/tools/tidy/src/deps.rs @@ -371,11 +371,6 @@ const PERMITTED_RUSTC_DEPENDENCIES: &[&str] = &[ "gimli", "gsgdt", "hashbrown", - "icu_list", - "icu_locale_core", - "icu_locale_fallback", - "icu_locale_fallback_data", - "icu_provider", "ident_case", "indexmap", "intl-memoizer", @@ -393,7 +388,6 @@ const PERMITTED_RUSTC_DEPENDENCIES: &[&str] = &[ "libc", "libloading", "linux-raw-sys", - "litemap", "lock_api", "log", "matchers", @@ -418,7 +412,6 @@ const PERMITTED_RUSTC_DEPENDENCIES: &[&str] = &[ "polonius-engine", "portable-atomic", // dependency for platforms doesn't support `AtomicU64` in std "portable-atomic-util", - "potential_utf", "ppv-lite86", "proc-macro-hack", "proc-macro2", @@ -520,14 +513,12 @@ const PERMITTED_RUSTC_DEPENDENCIES: &[&str] = &[ "windows-sys", "windows-threading", "wit-bindgen-rt@0.39.0", // pinned to a specific version due to using a binary blob: - "writeable", "yoke", "yoke-derive", "zerocopy", "zerocopy-derive", "zerofrom", "zerofrom-derive", - "zerotrie", "zerovec", "zerovec-derive", "zlib-rs", diff --git a/tests/assembly-llvm/c-variadic/m68k.rs b/tests/assembly-llvm/c-variadic/m68k.rs new file mode 100644 index 0000000000000..2e6898afa79b1 --- /dev/null +++ b/tests/assembly-llvm/c-variadic/m68k.rs @@ -0,0 +1,67 @@ +//@ add-minicore +//@ assembly-output: emit-asm +// +//@ compile-flags: -Copt-level=3 --target=m68k-unknown-linux-gnu +//@ needs-llvm-components: m68k +#![feature(c_variadic_experimental_arch, no_core, lang_items, intrinsics, rustc_attrs)] +#![no_core] +#![crate_type = "lib"] + +extern crate minicore; +use minicore::ffi::VaList; +use minicore::*; + +// This checks `va_arg` does the same thing as GCC. + +#[unsafe(no_mangle)] +unsafe extern "C" fn read_f64(ap: &mut VaList<'_>) -> f64 { + // CHECK-LABEL: read_f64 + // + // CHECK: move.l (4,%sp), %a0 + // CHECK-NEXT: move.l (%a0), %d0 + // CHECK-NEXT: move.l %d0, %d1 + // CHECK-NEXT: add.l #8, %d1 + // CHECK-NEXT: move.l %d1, (%a0) + // CHECK-NEXT: move.l %d0, %a0 + // CHECK-NEXT: move.l (%a0), %d0 + // CHECK-NEXT: move.l (4,%a0), %d1 + // CHECK-NEXT: rts + ap.next_arg() +} + +#[unsafe(no_mangle)] +unsafe extern "C" fn read_i32(ap: &mut VaList<'_>) -> i32 { + // CHECK-LABEL: read_i32 + // + // CHECK: move.l (4,%sp), %a0 + // CHECK-NEXT: move.l (%a0), %d0 + // CHECK-NEXT: move.l %d0, %d1 + // CHECK-NEXT: add.l #4, %d1 + // CHECK-NEXT: move.l %d1, (%a0) + // CHECK-NEXT: move.l %d0, %a0 + // CHECK-NEXT: move.l (%a0), %d0 + // CHECK-NEXT: rts + ap.next_arg() +} + +#[unsafe(no_mangle)] +unsafe extern "C" fn read_i64(ap: &mut VaList<'_>) -> i64 { + // CHECK-LABEL: read_i64 + // + // CHECK: move.l (4,%sp), %a0 + // CHECK-NEXT: move.l (%a0), %d0 + // CHECK-NEXT: move.l %d0, %d1 + // CHECK-NEXT: add.l #8, %d1 + // CHECK-NEXT: move.l %d1, (%a0) + // CHECK-NEXT: move.l %d0, %a0 + // CHECK-NEXT: move.l (%a0), %d0 + // CHECK-NEXT: move.l (4,%a0), %d1 + // CHECK-NEXT: rts + ap.next_arg() +} + +#[unsafe(no_mangle)] +unsafe extern "C" fn read_ptr(ap: &mut VaList<'_>) -> *const u8 { + // CHECK: read_ptr = read_i32 + ap.next_arg() +} diff --git a/tests/codegen-llvm/arm-abi/homogeneous-aggregate.rs b/tests/codegen-llvm/arm-abi/homogeneous-aggregate.rs index b627d45e84610..a6d1cc136639b 100644 --- a/tests/codegen-llvm/arm-abi/homogeneous-aggregate.rs +++ b/tests/codegen-llvm/arm-abi/homogeneous-aggregate.rs @@ -14,7 +14,7 @@ // Test that homogeneous aggregates are passed and returned with the correct ABI on 32-bit arm. #![feature(no_core, lang_items)] -#![feature(arm_target_feature)] +#![feature(arm_target_feature, f16, f128)] #![crate_type = "lib"] #![no_core] @@ -186,6 +186,20 @@ pub extern "C" fn test_floats_5(a: Floats5) { hint::black_box(a); } +// Only f32 and f64 qualify as an HFA base. + +// linux: define void @test_f16([2 x i32] %0) +#[unsafe(no_mangle)] +pub extern "C" fn test_f16(a: [f16; 3]) { + hint::black_box(a); +} + +// linux: define void @test_f128([2 x i64] %0) +#[unsafe(no_mangle)] +pub extern "C" fn test_f128(a: [f128; 1]) { + hint::black_box(a); +} + // Just a big struct, note how watchOS passes it indirectly. #[repr(C)] pub struct Ints6 { diff --git a/tests/codegen-llvm/complex-abi.rs b/tests/codegen-llvm/complex-abi.rs index 4e7cfec2c54cd..4717f581b39d3 100644 --- a/tests/codegen-llvm/complex-abi.rs +++ b/tests/codegen-llvm/complex-abi.rs @@ -140,7 +140,7 @@ pub extern "C" fn cplx_f16(x: Complex) -> Complex { // AARCH64_DARWIN: define{{.*}} [2 x half] @cplx_f16([2 x half] {{.*}}) // AARCH64_MSVC: define{{.*}} [2 x half] @cplx_f16([2 x half] {{.*}}) // ARM64EC: define{{.*}} [2 x half] @cplx_f16([2 x half] {{.*}}) - // ARM: define{{.*}} [2 x half] @cplx_f16([2 x half] {{.*}}) + // ARM: define{{.*}} i32 @cplx_f16([1 x i32] {{.*}}) // I686: define{{.*}} <2 x half> @cplx_f16(ptr {{.*}} byval([4 x i8]) {{.*}}) // LOONGARCH32: define{{.*}} { half, half } @cplx_f16({ half, half } {{.*}}) // LOONGARCH64: define{{.*}} { half, half } @cplx_f16({ half, half } {{.*}}) @@ -466,7 +466,7 @@ pub extern "C" fn wrapper_cplx_f16( // AARCH64_DARWIN: define{{.*}} [2 x half] @wrapper_cplx_f16([2 x half] {{.*}}) // AARCH64_MSVC: define{{.*}} [2 x half] @wrapper_cplx_f16([2 x half] {{.*}}) // ARM64EC: define{{.*}} [2 x half] @wrapper_cplx_f16([2 x half] {{.*}}) - // ARM: define{{.*}} [2 x half] @wrapper_cplx_f16([2 x half] {{.*}}) + // ARM: define{{.*}} i32 @wrapper_cplx_f16([1 x i32] {{.*}}) // I686: define{{.*}} <2 x half> @wrapper_cplx_f16(ptr {{.*}} byval([4 x i8]) {{.*}}) // LOONGARCH32: define{{.*}} { half, half } @wrapper_cplx_f16({ half, half } {{.*}}) // LOONGARCH64: define{{.*}} { half, half } @wrapper_cplx_f16({ half, half } {{.*}}) diff --git a/tests/ui-fulldeps/codegen-backend/llvm-target-features.stderr b/tests/ui-fulldeps/codegen-backend/llvm-target-features.stderr index 3faee3a631a12..26034d442fc6c 100644 --- a/tests/ui-fulldeps/codegen-backend/llvm-target-features.stderr +++ b/tests/ui-fulldeps/codegen-backend/llvm-target-features.stderr @@ -2,7 +2,7 @@ error: mixing codegen backends while using backend-specific target features may | = help: this crate has `-Zllvm-target-feature` set, which means different codegen backends could interpret the target features differently, or ignore them entirely = help: some target features modify the ABI so Rust crates compiled with different target features cannot be used together safely - = help: if you are sure this will not cause problems, you may use `-Cunsafe-allow-abi-mismatch=codegen-backend-name` to silence this warning + = help: if you are sure this will not cause problems, you may use `-Cunsafe-allow-abi-mismatch=codegen-backend-name` to silence this error error: aborting due to 1 previous error diff --git a/tests/ui/abi/bad-custom.edition2015.stderr b/tests/ui/abi/bad-custom.edition2015.stderr new file mode 100644 index 0000000000000..521a8919f4cfa --- /dev/null +++ b/tests/ui/abi/bad-custom.edition2015.stderr @@ -0,0 +1,512 @@ +error[E0670]: `async fn` is not permitted in Rust 2015 + --> $DIR/bad-custom.rs:142:1 + | +LL | async unsafe extern "custom" fn no_async_fn() { + | ^^^^^ to use `async fn`, switch to Rust 2018 or later + | + = help: pass `--edition 2024` to `rustc` + = note: for more on editions, read https://doc.rust-lang.org/edition-guide + +error: invalid signature for `extern "custom"` function + --> $DIR/bad-custom.rs:15:50 + | +LL | unsafe extern "custom" fn return_alias_unit() -> UnitAlias { + | ^^^^^^^^^ + | + = note: functions with the "custom" ABI cannot have any parameters or return type +help: remove the parameters and return type + | +LL - unsafe extern "custom" fn return_alias_unit() -> UnitAlias { +LL + unsafe extern "custom" fn return_alias_unit() { + | + +error: functions with the "custom" ABI must be unsafe + --> $DIR/bad-custom.rs:21:1 + | +LL | extern "custom" fn must_be_unsafe(a: i64) -> i64 { + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + | +help: add the `unsafe` keyword to this definition + | +LL | unsafe extern "custom" fn must_be_unsafe(a: i64) -> i64 { + | ++++++ + +error: invalid signature for `extern "custom"` function + --> $DIR/bad-custom.rs:21:35 + | +LL | extern "custom" fn must_be_unsafe(a: i64) -> i64 { + | ^^^^^^ ^^^ + | + = note: functions with the "custom" ABI cannot have any parameters or return type +help: remove the parameters and return type + | +LL - extern "custom" fn must_be_unsafe(a: i64) -> i64 { +LL + extern "custom" fn must_be_unsafe() { + | + +error: functions with the "custom" ABI must be unsafe + --> $DIR/bad-custom.rs:27:21 + | +LL | type MustbeUnsafe = extern "custom" fn(i64) -> i64; + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + | +help: add the `unsafe` keyword to this definition + | +LL | type MustbeUnsafe = unsafe extern "custom" fn(i64) -> i64; + | ++++++ + +error: invalid signature for `extern "custom"` function + --> $DIR/bad-custom.rs:27:40 + | +LL | type MustbeUnsafe = extern "custom" fn(i64) -> i64; + | ^^^ ^^^ + | + = note: functions with the "custom" ABI cannot have any parameters or return type +help: remove the parameters and return type + | +LL - type MustbeUnsafe = extern "custom" fn(i64) -> i64; +LL + type MustbeUnsafe = extern "custom" fn(); + | + +error: invalid signature for `extern "custom"` function + --> $DIR/bad-custom.rs:32:41 + | +LL | unsafe extern "custom" fn no_parameters(a: i64) { + | ^^^^^^ + | + = note: functions with the "custom" ABI cannot have any parameters or return type +help: remove the parameters and return type + | +LL - unsafe extern "custom" fn no_parameters(a: i64) { +LL + unsafe extern "custom" fn no_parameters() { + | + +error: invalid signature for `extern "custom"` function + --> $DIR/bad-custom.rs:37:47 + | +LL | type NoParameters = unsafe extern "custom" fn(i64); + | ^^^ + | + = note: functions with the "custom" ABI cannot have any parameters or return type +help: remove the parameters and return type + | +LL - type NoParameters = unsafe extern "custom" fn(i64); +LL + type NoParameters = unsafe extern "custom" fn(); + | + +error: invalid signature for `extern "custom"` function + --> $DIR/bad-custom.rs:41:47 + | +LL | unsafe extern "custom" fn no_return_type() -> i64 { + | ^^^ + | + = note: functions with the "custom" ABI cannot have any parameters or return type +help: remove the parameters and return type + | +LL - unsafe extern "custom" fn no_return_type() -> i64 { +LL + unsafe extern "custom" fn no_return_type() { + | + +error: invalid signature for `extern "custom"` function + --> $DIR/bad-custom.rs:46:52 + | +LL | type NoReturnType = unsafe extern "custom" fn() -> i64; + | ^^^ + | + = note: functions with the "custom" ABI cannot have any parameters or return type +help: remove the parameters and return type + | +LL - type NoReturnType = unsafe extern "custom" fn() -> i64; +LL + type NoReturnType = unsafe extern "custom" fn(); + | + +error: invalid signature for `extern "custom"` function + --> $DIR/bad-custom.rs:50:53 + | +LL | unsafe extern "custom" fn no_never_return_type() -> ! { + | ^ + | + = note: functions with the "custom" ABI cannot have any parameters or return type +help: remove the parameters and return type + | +LL - unsafe extern "custom" fn no_never_return_type() -> ! { +LL + unsafe extern "custom" fn no_never_return_type() { + | + +error: invalid signature for `extern "custom"` function + --> $DIR/bad-custom.rs:55:57 + | +LL | type NoNeverReturnType = unsafe extern "custom" fn() -> !; + | ^ + | + = note: functions with the "custom" ABI cannot have any parameters or return type +help: remove the parameters and return type + | +LL - type NoNeverReturnType = unsafe extern "custom" fn() -> !; +LL + type NoNeverReturnType = unsafe extern "custom" fn(); + | + +error: invalid signature for `extern "custom"` function + --> $DIR/bad-custom.rs:58:36 + | +LL | unsafe extern "custom" fn not_both(a: i64) -> i64 { + | ^^^^^^ ^^^ + | + = note: functions with the "custom" ABI cannot have any parameters or return type +help: remove the parameters and return type + | +LL - unsafe extern "custom" fn not_both(a: i64) -> i64 { +LL + unsafe extern "custom" fn not_both() { + | + +error: an `extern "custom"` function can only be declared externally or defined via naked functions + --> $DIR/bad-custom.rs:58:1 + | +LL | unsafe extern "custom" fn not_both(a: i64) -> i64 { + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + | +help: convert this to an `#[unsafe(naked)]` function + | +LL + #[unsafe(naked)] +LL | unsafe extern "custom" fn not_both(a: i64) -> i64 { + | + +error: invalid signature for `extern "custom"` function + --> $DIR/bad-custom.rs:64:42 + | +LL | type NotBoth = unsafe extern "custom" fn(i64) -> i64; + | ^^^ ^^^ + | + = note: functions with the "custom" ABI cannot have any parameters or return type +help: remove the parameters and return type + | +LL - type NotBoth = unsafe extern "custom" fn(i64) -> i64; +LL + type NotBoth = unsafe extern "custom" fn(); + | + +error: functions with the "custom" ABI must be unsafe + --> $DIR/bad-custom.rs:70:5 + | +LL | extern "custom" fn is_even(self) -> bool { + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + | +help: add the `unsafe` keyword to this definition + | +LL | unsafe extern "custom" fn is_even(self) -> bool { + | ++++++ + +error: invalid signature for `extern "custom"` function + --> $DIR/bad-custom.rs:70:32 + | +LL | extern "custom" fn is_even(self) -> bool { + | ^^^^ ^^^^ + | + = note: functions with the "custom" ABI cannot have any parameters or return type +help: remove the parameters and return type + | +LL - extern "custom" fn is_even(self) -> bool { +LL + extern "custom" fn is_even() { + | + +error: an `extern "custom"` function can only be declared externally or defined via naked functions + --> $DIR/bad-custom.rs:70:5 + | +LL | extern "custom" fn is_even(self) -> bool { + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + | +help: convert this to an `#[unsafe(naked)]` function + | +LL + #[unsafe(naked)] +LL | extern "custom" fn is_even(self) -> bool { + | + +error: functions with the "custom" ABI must be unsafe + --> $DIR/bad-custom.rs:79:5 + | +LL | extern "custom" fn bitwise_not(a: i64) -> i64 { + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + | +help: add the `unsafe` keyword to this definition + | +LL | unsafe extern "custom" fn bitwise_not(a: i64) -> i64 { + | ++++++ + +error: invalid signature for `extern "custom"` function + --> $DIR/bad-custom.rs:79:36 + | +LL | extern "custom" fn bitwise_not(a: i64) -> i64 { + | ^^^^^^ ^^^ + | + = note: functions with the "custom" ABI cannot have any parameters or return type +help: remove the parameters and return type + | +LL - extern "custom" fn bitwise_not(a: i64) -> i64 { +LL + extern "custom" fn bitwise_not() { + | + +error: an `extern "custom"` function can only be declared externally or defined via naked functions + --> $DIR/bad-custom.rs:79:5 + | +LL | extern "custom" fn bitwise_not(a: i64) -> i64 { + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + | +help: convert this to an `#[unsafe(naked)]` function + | +LL + #[unsafe(naked)] +LL | extern "custom" fn bitwise_not(a: i64) -> i64 { + | + +error: functions with the "custom" ABI must be unsafe + --> $DIR/bad-custom.rs:90:5 + | +LL | extern "custom" fn negate(a: i64) -> i64; + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + | +help: add the `unsafe` keyword to this definition + | +LL | unsafe extern "custom" fn negate(a: i64) -> i64; + | ++++++ + +error: invalid signature for `extern "custom"` function + --> $DIR/bad-custom.rs:90:31 + | +LL | extern "custom" fn negate(a: i64) -> i64; + | ^^^^^^ ^^^ + | + = note: functions with the "custom" ABI cannot have any parameters or return type +help: remove the parameters and return type + | +LL - extern "custom" fn negate(a: i64) -> i64; +LL + extern "custom" fn negate(); + | + +error: functions with the "custom" ABI must be unsafe + --> $DIR/bad-custom.rs:96:5 + | +LL | extern "custom" fn negate(a: i64) -> i64 { + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + | +help: add the `unsafe` keyword to this definition + | +LL | unsafe extern "custom" fn negate(a: i64) -> i64 { + | ++++++ + +error: invalid signature for `extern "custom"` function + --> $DIR/bad-custom.rs:96:31 + | +LL | extern "custom" fn negate(a: i64) -> i64 { + | ^^^^^^ ^^^ + | + = note: functions with the "custom" ABI cannot have any parameters or return type +help: remove the parameters and return type + | +LL - extern "custom" fn negate(a: i64) -> i64 { +LL + extern "custom" fn negate() { + | + +error: an `extern "custom"` function can only be declared externally or defined via naked functions + --> $DIR/bad-custom.rs:96:5 + | +LL | extern "custom" fn negate(a: i64) -> i64 { + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + | +help: convert this to an `#[unsafe(naked)]` function + | +LL + #[unsafe(naked)] +LL | extern "custom" fn negate(a: i64) -> i64 { + | + +error: invalid signature for `extern "custom"` function + --> $DIR/bad-custom.rs:105:18 + | +LL | fn increment(a: i64) -> i64; + | ^^^^^^ ^^^ + | + = note: functions with the "custom" ABI cannot have any parameters or return type +help: remove the parameters and return type + | +LL - fn increment(a: i64) -> i64; +LL + fn increment(); + | + +error: foreign functions with the "custom" ABI cannot be safe + --> $DIR/bad-custom.rs:108:5 + | +LL | safe fn extern_cannot_be_safe(); + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + | +help: remove the `safe` keyword from this definition + | +LL - safe fn extern_cannot_be_safe(); +LL + fn extern_cannot_be_safe(); + | + +error: function pointers cannot be declared with `safe` safety qualifier + --> $DIR/bad-custom.rs:112:13 + | +LL | type Safe = safe extern "custom" fn(); + | ^^^^ + | +help: remove the `safe` qualifier + | +LL - type Safe = safe extern "custom" fn(); +LL + type Safe = extern "custom" fn(); + | + +error: invalid signature for `extern "custom"` function + --> $DIR/bad-custom.rs:115:40 + | +LL | fn caller(f: unsafe extern "custom" fn(i64) -> i64, mut x: i64) -> i64 { + | ^^^ ^^^ + | + = note: functions with the "custom" ABI cannot have any parameters or return type +help: remove the parameters and return type + | +LL - fn caller(f: unsafe extern "custom" fn(i64) -> i64, mut x: i64) -> i64 { +LL + fn caller(f: unsafe extern "custom" fn(), mut x: i64) -> i64 { + | + +error: invalid signature for `extern "custom"` function + --> $DIR/bad-custom.rs:121:48 + | +LL | fn caller_by_ref(f: &unsafe extern "custom" fn(i64) -> i64, mut x: i64) -> i64 { + | ^^^ ^^^ + | + = note: functions with the "custom" ABI cannot have any parameters or return type +help: remove the parameters and return type + | +LL - fn caller_by_ref(f: &unsafe extern "custom" fn(i64) -> i64, mut x: i64) -> i64 { +LL + fn caller_by_ref(f: &unsafe extern "custom" fn(), mut x: i64) -> i64 { + | + +error: invalid signature for `extern "custom"` function + --> $DIR/bad-custom.rs:127:40 + | +LL | type Alias = unsafe extern "custom" fn(i64) -> i64; + | ^^^ ^^^ + | + = note: functions with the "custom" ABI cannot have any parameters or return type +help: remove the parameters and return type + | +LL - type Alias = unsafe extern "custom" fn(i64) -> i64; +LL + type Alias = unsafe extern "custom" fn(); + | + +error: an `extern "custom"` function cannot be marked `#[cold]` + --> $DIR/bad-custom.rs:155:1 + | +LL | #[cold] + | ------- help: remove the `#[cold]` attribute +LL | #[unsafe(naked)] +LL | unsafe extern "custom" fn no_cold_attribute() { + | ^^^^^^^---------------^^^^^^^^^^^^^^^^^^^^^^^ + | | + | `extern "custom"` because of this + +error[E0277]: expected `Fn()` signature, found `unsafe extern "custom" fn()` + --> $DIR/bad-custom.rs:148:64 + | +LL | fn no_promotion_to_fn_trait(f: unsafe extern "custom" fn()) -> impl Fn() { + | ^^^^^^^^^ call the function in a closure: `|| unsafe { /* code */ }` +LL | +LL | f + | - return type was inferred to be `unsafe extern "custom" fn()` here + | + = help: the trait `Fn()` is not implemented for `unsafe extern "custom" fn()` + = note: wrap the `unsafe extern "custom" fn()` in a closure with no arguments: `|| { /* code */ }` + = note: unsafe function cannot be called generically without an unsafe block + +error: functions with the "custom" ABI cannot be called + --> $DIR/bad-custom.rs:117:14 + | +LL | unsafe { f(x) } + | ^^^^ + | +note: an `extern "custom"` function can only be called using inline assembly + --> $DIR/bad-custom.rs:117:14 + | +LL | unsafe { f(x) } + | ^^^^ + +error: functions with the "custom" ABI cannot be called + --> $DIR/bad-custom.rs:123:14 + | +LL | unsafe { f(x) } + | ^^^^ + | +note: an `extern "custom"` function can only be called using inline assembly + --> $DIR/bad-custom.rs:123:14 + | +LL | unsafe { f(x) } + | ^^^^ + +error: functions with the "custom" ABI cannot be called + --> $DIR/bad-custom.rs:131:14 + | +LL | unsafe { f(x) } + | ^^^^ + | +note: an `extern "custom"` function can only be called using inline assembly + --> $DIR/bad-custom.rs:131:14 + | +LL | unsafe { f(x) } + | ^^^^ + +error: functions with the "custom" ABI cannot be called + --> $DIR/bad-custom.rs:162:20 + | +LL | assert_eq!(not_both(21), 42); + | ^^^^^^^^^^^^ + | +note: an `extern "custom"` function can only be called using inline assembly + --> $DIR/bad-custom.rs:162:20 + | +LL | assert_eq!(not_both(21), 42); + | ^^^^^^^^^^^^ + +error: functions with the "custom" ABI cannot be called + --> $DIR/bad-custom.rs:165:29 + | +LL | assert_eq!(unsafe { increment(41) }, 42); + | ^^^^^^^^^^^^^ + | +note: an `extern "custom"` function can only be called using inline assembly + --> $DIR/bad-custom.rs:165:29 + | +LL | assert_eq!(unsafe { increment(41) }, 42); + | ^^^^^^^^^^^^^ + +error: functions with the "custom" ABI cannot be called + --> $DIR/bad-custom.rs:168:17 + | +LL | assert!(Thing(41).is_even()); + | ^^^^^^^^^^^^^^^^^^^ + | +note: an `extern "custom"` function can only be called using inline assembly + --> $DIR/bad-custom.rs:168:17 + | +LL | assert!(Thing(41).is_even()); + | ^^^^^^^^^^^^^^^^^^^ + +error: functions with the "custom" ABI cannot be called + --> $DIR/bad-custom.rs:171:20 + | +LL | assert_eq!(Thing::bitwise_not(42), !42); + | ^^^^^^^^^^^^^^^^^^^^^^ + | +note: an `extern "custom"` function can only be called using inline assembly + --> $DIR/bad-custom.rs:171:20 + | +LL | assert_eq!(Thing::bitwise_not(42), !42); + | ^^^^^^^^^^^^^^^^^^^^^^ + +error[E0015]: inline assembly is not allowed in constant functions + --> $DIR/bad-custom.rs:137:5 + | +LL | std::arch::naked_asm!("") + | ^^^^^^^^^^^^^^^^^^^^^^^^^ + +error: aborting due to 42 previous errors + +Some errors have detailed explanations: E0015, E0277, E0670. +For more information about an error, try `rustc --explain E0015`. diff --git a/tests/ui/abi/bad-custom.stderr b/tests/ui/abi/bad-custom.edition2018.stderr similarity index 91% rename from tests/ui/abi/bad-custom.stderr rename to tests/ui/abi/bad-custom.edition2018.stderr index 64e2c642da0d8..f83bd4df0fdae 100644 --- a/tests/ui/abi/bad-custom.stderr +++ b/tests/ui/abi/bad-custom.edition2018.stderr @@ -1,5 +1,5 @@ error: invalid signature for `extern "custom"` function - --> $DIR/bad-custom.rs:13:50 + --> $DIR/bad-custom.rs:15:50 | LL | unsafe extern "custom" fn return_alias_unit() -> UnitAlias { | ^^^^^^^^^ @@ -12,7 +12,7 @@ LL + unsafe extern "custom" fn return_alias_unit() { | error: functions with the "custom" ABI must be unsafe - --> $DIR/bad-custom.rs:19:1 + --> $DIR/bad-custom.rs:21:1 | LL | extern "custom" fn must_be_unsafe(a: i64) -> i64 { | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ @@ -23,7 +23,7 @@ LL | unsafe extern "custom" fn must_be_unsafe(a: i64) -> i64 { | ++++++ error: invalid signature for `extern "custom"` function - --> $DIR/bad-custom.rs:19:35 + --> $DIR/bad-custom.rs:21:35 | LL | extern "custom" fn must_be_unsafe(a: i64) -> i64 { | ^^^^^^ ^^^ @@ -36,7 +36,7 @@ LL + extern "custom" fn must_be_unsafe() { | error: functions with the "custom" ABI must be unsafe - --> $DIR/bad-custom.rs:25:21 + --> $DIR/bad-custom.rs:27:21 | LL | type MustbeUnsafe = extern "custom" fn(i64) -> i64; | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ @@ -47,7 +47,7 @@ LL | type MustbeUnsafe = unsafe extern "custom" fn(i64) -> i64; | ++++++ error: invalid signature for `extern "custom"` function - --> $DIR/bad-custom.rs:25:40 + --> $DIR/bad-custom.rs:27:40 | LL | type MustbeUnsafe = extern "custom" fn(i64) -> i64; | ^^^ ^^^ @@ -60,7 +60,7 @@ LL + type MustbeUnsafe = extern "custom" fn(); | error: invalid signature for `extern "custom"` function - --> $DIR/bad-custom.rs:30:41 + --> $DIR/bad-custom.rs:32:41 | LL | unsafe extern "custom" fn no_parameters(a: i64) { | ^^^^^^ @@ -73,7 +73,7 @@ LL + unsafe extern "custom" fn no_parameters() { | error: invalid signature for `extern "custom"` function - --> $DIR/bad-custom.rs:35:47 + --> $DIR/bad-custom.rs:37:47 | LL | type NoParameters = unsafe extern "custom" fn(i64); | ^^^ @@ -86,7 +86,7 @@ LL + type NoParameters = unsafe extern "custom" fn(); | error: invalid signature for `extern "custom"` function - --> $DIR/bad-custom.rs:39:47 + --> $DIR/bad-custom.rs:41:47 | LL | unsafe extern "custom" fn no_return_type() -> i64 { | ^^^ @@ -99,7 +99,7 @@ LL + unsafe extern "custom" fn no_return_type() { | error: invalid signature for `extern "custom"` function - --> $DIR/bad-custom.rs:44:52 + --> $DIR/bad-custom.rs:46:52 | LL | type NoReturnType = unsafe extern "custom" fn() -> i64; | ^^^ @@ -112,7 +112,7 @@ LL + type NoReturnType = unsafe extern "custom" fn(); | error: invalid signature for `extern "custom"` function - --> $DIR/bad-custom.rs:48:53 + --> $DIR/bad-custom.rs:50:53 | LL | unsafe extern "custom" fn no_never_return_type() -> ! { | ^ @@ -125,7 +125,7 @@ LL + unsafe extern "custom" fn no_never_return_type() { | error: invalid signature for `extern "custom"` function - --> $DIR/bad-custom.rs:53:57 + --> $DIR/bad-custom.rs:55:57 | LL | type NoNeverReturnType = unsafe extern "custom" fn() -> !; | ^ @@ -138,7 +138,7 @@ LL + type NoNeverReturnType = unsafe extern "custom" fn(); | error: invalid signature for `extern "custom"` function - --> $DIR/bad-custom.rs:56:36 + --> $DIR/bad-custom.rs:58:36 | LL | unsafe extern "custom" fn not_both(a: i64) -> i64 { | ^^^^^^ ^^^ @@ -151,7 +151,7 @@ LL + unsafe extern "custom" fn not_both() { | error: an `extern "custom"` function can only be declared externally or defined via naked functions - --> $DIR/bad-custom.rs:56:1 + --> $DIR/bad-custom.rs:58:1 | LL | unsafe extern "custom" fn not_both(a: i64) -> i64 { | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ @@ -163,7 +163,7 @@ LL | unsafe extern "custom" fn not_both(a: i64) -> i64 { | error: invalid signature for `extern "custom"` function - --> $DIR/bad-custom.rs:62:42 + --> $DIR/bad-custom.rs:64:42 | LL | type NotBoth = unsafe extern "custom" fn(i64) -> i64; | ^^^ ^^^ @@ -176,7 +176,7 @@ LL + type NotBoth = unsafe extern "custom" fn(); | error: functions with the "custom" ABI must be unsafe - --> $DIR/bad-custom.rs:68:5 + --> $DIR/bad-custom.rs:70:5 | LL | extern "custom" fn is_even(self) -> bool { | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ @@ -187,7 +187,7 @@ LL | unsafe extern "custom" fn is_even(self) -> bool { | ++++++ error: invalid signature for `extern "custom"` function - --> $DIR/bad-custom.rs:68:32 + --> $DIR/bad-custom.rs:70:32 | LL | extern "custom" fn is_even(self) -> bool { | ^^^^ ^^^^ @@ -200,7 +200,7 @@ LL + extern "custom" fn is_even() { | error: an `extern "custom"` function can only be declared externally or defined via naked functions - --> $DIR/bad-custom.rs:68:5 + --> $DIR/bad-custom.rs:70:5 | LL | extern "custom" fn is_even(self) -> bool { | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ @@ -212,7 +212,7 @@ LL | extern "custom" fn is_even(self) -> bool { | error: functions with the "custom" ABI must be unsafe - --> $DIR/bad-custom.rs:77:5 + --> $DIR/bad-custom.rs:79:5 | LL | extern "custom" fn bitwise_not(a: i64) -> i64 { | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ @@ -223,7 +223,7 @@ LL | unsafe extern "custom" fn bitwise_not(a: i64) -> i64 { | ++++++ error: invalid signature for `extern "custom"` function - --> $DIR/bad-custom.rs:77:36 + --> $DIR/bad-custom.rs:79:36 | LL | extern "custom" fn bitwise_not(a: i64) -> i64 { | ^^^^^^ ^^^ @@ -236,7 +236,7 @@ LL + extern "custom" fn bitwise_not() { | error: an `extern "custom"` function can only be declared externally or defined via naked functions - --> $DIR/bad-custom.rs:77:5 + --> $DIR/bad-custom.rs:79:5 | LL | extern "custom" fn bitwise_not(a: i64) -> i64 { | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ @@ -248,7 +248,7 @@ LL | extern "custom" fn bitwise_not(a: i64) -> i64 { | error: functions with the "custom" ABI must be unsafe - --> $DIR/bad-custom.rs:88:5 + --> $DIR/bad-custom.rs:90:5 | LL | extern "custom" fn negate(a: i64) -> i64; | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ @@ -259,7 +259,7 @@ LL | unsafe extern "custom" fn negate(a: i64) -> i64; | ++++++ error: invalid signature for `extern "custom"` function - --> $DIR/bad-custom.rs:88:31 + --> $DIR/bad-custom.rs:90:31 | LL | extern "custom" fn negate(a: i64) -> i64; | ^^^^^^ ^^^ @@ -272,7 +272,7 @@ LL + extern "custom" fn negate(); | error: functions with the "custom" ABI must be unsafe - --> $DIR/bad-custom.rs:94:5 + --> $DIR/bad-custom.rs:96:5 | LL | extern "custom" fn negate(a: i64) -> i64 { | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ @@ -283,7 +283,7 @@ LL | unsafe extern "custom" fn negate(a: i64) -> i64 { | ++++++ error: invalid signature for `extern "custom"` function - --> $DIR/bad-custom.rs:94:31 + --> $DIR/bad-custom.rs:96:31 | LL | extern "custom" fn negate(a: i64) -> i64 { | ^^^^^^ ^^^ @@ -296,7 +296,7 @@ LL + extern "custom" fn negate() { | error: an `extern "custom"` function can only be declared externally or defined via naked functions - --> $DIR/bad-custom.rs:94:5 + --> $DIR/bad-custom.rs:96:5 | LL | extern "custom" fn negate(a: i64) -> i64 { | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ @@ -308,7 +308,7 @@ LL | extern "custom" fn negate(a: i64) -> i64 { | error: invalid signature for `extern "custom"` function - --> $DIR/bad-custom.rs:103:18 + --> $DIR/bad-custom.rs:105:18 | LL | fn increment(a: i64) -> i64; | ^^^^^^ ^^^ @@ -321,7 +321,7 @@ LL + fn increment(); | error: foreign functions with the "custom" ABI cannot be safe - --> $DIR/bad-custom.rs:106:5 + --> $DIR/bad-custom.rs:108:5 | LL | safe fn extern_cannot_be_safe(); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ @@ -333,7 +333,7 @@ LL + fn extern_cannot_be_safe(); | error: function pointers cannot be declared with `safe` safety qualifier - --> $DIR/bad-custom.rs:110:13 + --> $DIR/bad-custom.rs:112:13 | LL | type Safe = safe extern "custom" fn(); | ^^^^ @@ -345,7 +345,7 @@ LL + type Safe = extern "custom" fn(); | error: invalid signature for `extern "custom"` function - --> $DIR/bad-custom.rs:113:40 + --> $DIR/bad-custom.rs:115:40 | LL | fn caller(f: unsafe extern "custom" fn(i64) -> i64, mut x: i64) -> i64 { | ^^^ ^^^ @@ -358,7 +358,7 @@ LL + fn caller(f: unsafe extern "custom" fn(), mut x: i64) -> i64 { | error: invalid signature for `extern "custom"` function - --> $DIR/bad-custom.rs:119:48 + --> $DIR/bad-custom.rs:121:48 | LL | fn caller_by_ref(f: &unsafe extern "custom" fn(i64) -> i64, mut x: i64) -> i64 { | ^^^ ^^^ @@ -371,7 +371,7 @@ LL + fn caller_by_ref(f: &unsafe extern "custom" fn(), mut x: i64) -> i64 { | error: invalid signature for `extern "custom"` function - --> $DIR/bad-custom.rs:125:40 + --> $DIR/bad-custom.rs:127:40 | LL | type Alias = unsafe extern "custom" fn(i64) -> i64; | ^^^ ^^^ @@ -384,7 +384,7 @@ LL + type Alias = unsafe extern "custom" fn(); | error: functions with the "custom" ABI cannot be `async` - --> $DIR/bad-custom.rs:139:1 + --> $DIR/bad-custom.rs:142:1 | LL | async unsafe extern "custom" fn no_async_fn() { | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ @@ -396,7 +396,7 @@ LL + unsafe extern "custom" fn no_async_fn() { | error: an `extern "custom"` function can only be declared externally or defined via naked functions - --> $DIR/bad-custom.rs:139:1 + --> $DIR/bad-custom.rs:142:1 | LL | async unsafe extern "custom" fn no_async_fn() { | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ @@ -408,7 +408,7 @@ LL | async unsafe extern "custom" fn no_async_fn() { | error: an `extern "custom"` function cannot be marked `#[cold]` - --> $DIR/bad-custom.rs:151:1 + --> $DIR/bad-custom.rs:155:1 | LL | #[cold] | ------- help: remove the `#[cold]` attribute @@ -419,7 +419,7 @@ LL | unsafe extern "custom" fn no_cold_attribute() { | `extern "custom"` because of this error[E0277]: expected `Fn()` signature, found `unsafe extern "custom" fn()` - --> $DIR/bad-custom.rs:144:64 + --> $DIR/bad-custom.rs:148:64 | LL | fn no_promotion_to_fn_trait(f: unsafe extern "custom" fn()) -> impl Fn() { | ^^^^^^^^^ call the function in a closure: `|| unsafe { /* code */ }` @@ -432,91 +432,91 @@ LL | f = note: unsafe function cannot be called generically without an unsafe block error: functions with the "custom" ABI cannot be called - --> $DIR/bad-custom.rs:115:14 + --> $DIR/bad-custom.rs:117:14 | LL | unsafe { f(x) } | ^^^^ | note: an `extern "custom"` function can only be called using inline assembly - --> $DIR/bad-custom.rs:115:14 + --> $DIR/bad-custom.rs:117:14 | LL | unsafe { f(x) } | ^^^^ error: functions with the "custom" ABI cannot be called - --> $DIR/bad-custom.rs:121:14 + --> $DIR/bad-custom.rs:123:14 | LL | unsafe { f(x) } | ^^^^ | note: an `extern "custom"` function can only be called using inline assembly - --> $DIR/bad-custom.rs:121:14 + --> $DIR/bad-custom.rs:123:14 | LL | unsafe { f(x) } | ^^^^ error: functions with the "custom" ABI cannot be called - --> $DIR/bad-custom.rs:129:14 + --> $DIR/bad-custom.rs:131:14 | LL | unsafe { f(x) } | ^^^^ | note: an `extern "custom"` function can only be called using inline assembly - --> $DIR/bad-custom.rs:129:14 + --> $DIR/bad-custom.rs:131:14 | LL | unsafe { f(x) } | ^^^^ error: functions with the "custom" ABI cannot be called - --> $DIR/bad-custom.rs:158:20 + --> $DIR/bad-custom.rs:162:20 | LL | assert_eq!(not_both(21), 42); | ^^^^^^^^^^^^ | note: an `extern "custom"` function can only be called using inline assembly - --> $DIR/bad-custom.rs:158:20 + --> $DIR/bad-custom.rs:162:20 | LL | assert_eq!(not_both(21), 42); | ^^^^^^^^^^^^ error: functions with the "custom" ABI cannot be called - --> $DIR/bad-custom.rs:161:29 + --> $DIR/bad-custom.rs:165:29 | LL | assert_eq!(unsafe { increment(41) }, 42); | ^^^^^^^^^^^^^ | note: an `extern "custom"` function can only be called using inline assembly - --> $DIR/bad-custom.rs:161:29 + --> $DIR/bad-custom.rs:165:29 | LL | assert_eq!(unsafe { increment(41) }, 42); | ^^^^^^^^^^^^^ error: functions with the "custom" ABI cannot be called - --> $DIR/bad-custom.rs:164:17 + --> $DIR/bad-custom.rs:168:17 | LL | assert!(Thing(41).is_even()); | ^^^^^^^^^^^^^^^^^^^ | note: an `extern "custom"` function can only be called using inline assembly - --> $DIR/bad-custom.rs:164:17 + --> $DIR/bad-custom.rs:168:17 | LL | assert!(Thing(41).is_even()); | ^^^^^^^^^^^^^^^^^^^ error: functions with the "custom" ABI cannot be called - --> $DIR/bad-custom.rs:167:20 + --> $DIR/bad-custom.rs:171:20 | LL | assert_eq!(Thing::bitwise_not(42), !42); | ^^^^^^^^^^^^^^^^^^^^^^ | note: an `extern "custom"` function can only be called using inline assembly - --> $DIR/bad-custom.rs:167:20 + --> $DIR/bad-custom.rs:171:20 | LL | assert_eq!(Thing::bitwise_not(42), !42); | ^^^^^^^^^^^^^^^^^^^^^^ error[E0015]: inline assembly is not allowed in constant functions - --> $DIR/bad-custom.rs:135:5 + --> $DIR/bad-custom.rs:137:5 | LL | std::arch::naked_asm!("") | ^^^^^^^^^^^^^^^^^^^^^^^^^ diff --git a/tests/ui/abi/bad-custom.rs b/tests/ui/abi/bad-custom.rs index b4d2325683b44..8b28328242a34 100644 --- a/tests/ui/abi/bad-custom.rs +++ b/tests/ui/abi/bad-custom.rs @@ -1,6 +1,8 @@ -//@ edition: 2021 //@ check-fail //@ needs-asm-support +//@ revisions: edition2015 edition2018 +//@[edition2015] edition: 2015 +//@[edition2018] edition: 2018.. #[unsafe(naked)] unsafe extern "custom" fn return_explicit_unit() -> () { @@ -136,9 +138,11 @@ const unsafe extern "custom" fn no_const_fn() { //~^ ERROR inline assembly is not allowed in constant functions } +#[cfg(edition2018)] async unsafe extern "custom" fn no_async_fn() { - //~^ ERROR an `extern "custom"` function can only be declared externally or defined via naked functions - //~| ERROR functions with the "custom" ABI cannot be `async` + //[edition2015]~^ ERROR `async fn` is not permitted in Rust 2015 + //[edition2018]~^^ ERROR an `extern "custom"` function can only be declared externally or defined via naked functions + //[edition2018]~| ERROR functions with the "custom" ABI cannot be `async` } fn no_promotion_to_fn_trait(f: unsafe extern "custom" fn()) -> impl Fn() { diff --git a/tests/ui/asm/aarch64/aarch64-sve.rs b/tests/ui/asm/aarch64/aarch64-sve.rs index ac19b7bc98131..adc0a3e34b56c 100644 --- a/tests/ui/asm/aarch64/aarch64-sve.rs +++ b/tests/ui/asm/aarch64/aarch64-sve.rs @@ -18,3 +18,5 @@ fn f(x: f64) { asm!("", out("ffr") _); } } + +//@ reference: asm.register-operands.supported-register-classes diff --git a/tests/ui/asm/aarch64/arm64ec-sve.rs b/tests/ui/asm/aarch64/arm64ec-sve.rs index 05830aee8a974..14f11320acedc 100644 --- a/tests/ui/asm/aarch64/arm64ec-sve.rs +++ b/tests/ui/asm/aarch64/arm64ec-sve.rs @@ -21,3 +21,5 @@ fn f(x: f64) { //~^ ERROR cannot use register `ffr` } } + +//@ reference: asm.register-names.not-for-io diff --git a/tests/ui/asm/aarch64/bad-options.rs b/tests/ui/asm/aarch64/bad-options.rs index ebba9255d3240..2b3d5b27021cc 100644 --- a/tests/ui/asm/aarch64/bad-options.rs +++ b/tests/ui/asm/aarch64/bad-options.rs @@ -44,3 +44,10 @@ global_asm!("", options(nostack)); //~^ ERROR the `nostack` option cannot be used with `global_asm!` global_asm!("", options(preserves_flags)); //~^ ERROR the `preserves_flags` option cannot be used with `global_asm!` + +//@ reference: asm.abi-clobbers.must-specify +//@ reference: asm.abi-clobbers.supported-abis +//@ reference: asm.options.checks-mutually-exclusive +//@ reference: asm.options.checks-noreturn +//@ reference: asm.options.checks-pure +//@ reference: asm.options.global_asm-restriction diff --git a/tests/ui/asm/aarch64/bad-reg.rs b/tests/ui/asm/aarch64/bad-reg.rs index daaca4746cf37..e54a7737ebde3 100644 --- a/tests/ui/asm/aarch64/bad-reg.rs +++ b/tests/ui/asm/aarch64/bad-reg.rs @@ -63,3 +63,11 @@ fn main() { asm!("", in("v0") foo, lateout("q0") bar); } } + +//@ reference: asm.operand-type.supported-operands-lateout +//@ reference: asm.register-names.not-for-io +//@ reference: asm.register-operands.equivalence-to-base-register +//@ reference: asm.register-operands.error-two-operands +//@ reference: asm.register-operands.register-or-class +//@ reference: asm.register-operands.supported-register-classes +//@ reference: asm.template-modifiers.supported-modifiers diff --git a/tests/ui/asm/aarch64/const.rs b/tests/ui/asm/aarch64/const.rs index 3eab5138d7d79..90d27fc37c4eb 100644 --- a/tests/ui/asm/aarch64/const.rs +++ b/tests/ui/asm/aarch64/const.rs @@ -38,3 +38,5 @@ fn main() { global_asm!("mov x0, {}", const 5); global_asm!("mov x0, {}", const constfn(5)); global_asm!("mov x0, {}", const constfn(5) + constfn(5)); + +//@ reference: asm.operand-type.supported-operands-const diff --git a/tests/ui/asm/aarch64/llvm-58384.rs b/tests/ui/asm/aarch64/llvm-58384.rs index b11b2f3c0b9ae..c28aa38481528 100644 --- a/tests/ui/asm/aarch64/llvm-58384.rs +++ b/tests/ui/asm/aarch64/llvm-58384.rs @@ -14,3 +14,5 @@ fn main() { } assert_eq!(a, 435); } + +//@ reference: asm.operand-type.supported-operands-inout-arrow diff --git a/tests/ui/asm/aarch64/parse-error.rs b/tests/ui/asm/aarch64/parse-error.rs index f9ee9a1802b16..5612d05af1e72 100644 --- a/tests/ui/asm/aarch64/parse-error.rs +++ b/tests/ui/asm/aarch64/parse-error.rs @@ -24,3 +24,5 @@ fn main() { //~^^ ERROR attempt to use a non-constant value in a constant } } + +//@ reference: asm.ts-args.positional-first diff --git a/tests/ui/asm/aarch64/srcloc.rs b/tests/ui/asm/aarch64/srcloc.rs index b5e77c4023970..c17d8d3f03f61 100644 --- a/tests/ui/asm/aarch64/srcloc.rs +++ b/tests/ui/asm/aarch64/srcloc.rs @@ -134,3 +134,6 @@ fn main() { //~^^ ERROR: unrecognized instruction mnemonic } } + +//@ reference: asm.ts-args.one-or-more +//@ reference: asm.validity.non-exhaustive diff --git a/tests/ui/asm/aarch64/sym.rs b/tests/ui/asm/aarch64/sym.rs index 27113c694aac7..e3190275ad6f3 100644 --- a/tests/ui/asm/aarch64/sym.rs +++ b/tests/ui/asm/aarch64/sym.rs @@ -83,3 +83,5 @@ fn main() { .join() .unwrap(); } + +//@ reference: asm.operand-type.supported-operands-sym diff --git a/tests/ui/asm/aarch64/type-check-2-2.rs b/tests/ui/asm/aarch64/type-check-2-2.rs index d729212c4d06a..cae9e920b2c86 100644 --- a/tests/ui/asm/aarch64/type-check-2-2.rs +++ b/tests/ui/asm/aarch64/type-check-2-2.rs @@ -33,3 +33,7 @@ fn main() { // Sym operands must point to a function or static } } + +//@ reference: asm.operand-type.supported-operands-in +//@ reference: asm.operand-type.supported-operands-inout +//@ reference: asm.operand-type.supported-operands-out diff --git a/tests/ui/asm/aarch64/type-check-2.rs b/tests/ui/asm/aarch64/type-check-2.rs index 0faa6d904a5ce..ea8f31822e3f1 100644 --- a/tests/ui/asm/aarch64/type-check-2.rs +++ b/tests/ui/asm/aarch64/type-check-2.rs @@ -56,3 +56,5 @@ fn main() { asm!("{}", in(reg) u); } } + +//@ reference: asm.register-operands.allowed-types diff --git a/tests/ui/asm/aarch64/type-check-3.rs b/tests/ui/asm/aarch64/type-check-3.rs index 6c01a3380f169..20bbfc3b653be 100644 --- a/tests/ui/asm/aarch64/type-check-3.rs +++ b/tests/ui/asm/aarch64/type-check-3.rs @@ -115,3 +115,9 @@ fn main() { asm!("{:x}", inout(reg) main => val_u64); } } + +//@ reference: asm.operand-type.supported-operands-inout-arrow +//@ reference: asm.register-operands.separate-input-output +//@ reference: asm.register-operands.value-type-constraints +//@ reference: asm.template-modifiers.smaller-value +//@ reference: asm.template-modifiers.supported-modifiers diff --git a/tests/ui/asm/arm-low-dreg.rs b/tests/ui/asm/arm-low-dreg.rs index 26f594f8362af..f8a8640696cda 100644 --- a/tests/ui/asm/arm-low-dreg.rs +++ b/tests/ui/asm/arm-low-dreg.rs @@ -20,3 +20,5 @@ fn f(x: f64) -> f64 { } out } + +//@ reference: asm.register-operands.supported-register-classes diff --git a/tests/ui/asm/bad-template.aarch64.stderr b/tests/ui/asm/bad-template.aarch64.stderr index 268fcceb14a50..49a808b605417 100644 --- a/tests/ui/asm/bad-template.aarch64.stderr +++ b/tests/ui/asm/bad-template.aarch64.stderr @@ -1,5 +1,5 @@ error: invalid reference to argument at index 0 - --> $DIR/bad-template.rs:22:15 + --> $DIR/bad-template.rs:20:15 | LL | asm!("{}"); | ^^ from here @@ -7,7 +7,7 @@ LL | asm!("{}"); = note: no arguments were given error: invalid reference to argument at index 1 - --> $DIR/bad-template.rs:24:15 + --> $DIR/bad-template.rs:22:15 | LL | asm!("{1}", in(reg) foo); | ^^^ from here @@ -15,7 +15,7 @@ LL | asm!("{1}", in(reg) foo); = note: there is 1 argument error: argument never used - --> $DIR/bad-template.rs:24:21 + --> $DIR/bad-template.rs:22:21 | LL | asm!("{1}", in(reg) foo); | ^^^^^^^^^^^ argument never used @@ -23,13 +23,13 @@ LL | asm!("{1}", in(reg) foo); = help: if this argument is intentionally unused, consider using it in an asm comment: `"/* {0} */"` error: there is no argument named `a` - --> $DIR/bad-template.rs:27:16 + --> $DIR/bad-template.rs:25:16 | LL | asm!("{a}"); | ^ error: invalid reference to argument at index 0 - --> $DIR/bad-template.rs:29:15 + --> $DIR/bad-template.rs:27:15 | LL | asm!("{}", a = in(reg) foo); | ^^ --------------- named argument @@ -38,13 +38,13 @@ LL | asm!("{}", a = in(reg) foo); | = note: no positional arguments were given note: named arguments cannot be referenced by position - --> $DIR/bad-template.rs:29:20 + --> $DIR/bad-template.rs:27:20 | LL | asm!("{}", a = in(reg) foo); | ^^^^^^^^^^^^^^^ error: named argument never used - --> $DIR/bad-template.rs:29:20 + --> $DIR/bad-template.rs:27:20 | LL | asm!("{}", a = in(reg) foo); | ^^^^^^^^^^^^^^^ named argument never used @@ -52,7 +52,7 @@ LL | asm!("{}", a = in(reg) foo); = help: if this argument is intentionally unused, consider using it in an asm comment: `"/* {a} */"` error: invalid reference to argument at index 1 - --> $DIR/bad-template.rs:32:15 + --> $DIR/bad-template.rs:30:15 | LL | asm!("{1}", a = in(reg) foo); | ^^^ from here @@ -60,7 +60,7 @@ LL | asm!("{1}", a = in(reg) foo); = note: no positional arguments were given error: named argument never used - --> $DIR/bad-template.rs:32:21 + --> $DIR/bad-template.rs:30:21 | LL | asm!("{1}", a = in(reg) foo); | ^^^^^^^^^^^^^^^ named argument never used @@ -68,7 +68,7 @@ LL | asm!("{1}", a = in(reg) foo); = help: if this argument is intentionally unused, consider using it in an asm comment: `"/* {a} */"` error: invalid reference to argument at index 0 - --> $DIR/bad-template.rs:39:15 + --> $DIR/bad-template.rs:37:15 | LL | asm!("{}", in("x0") foo); | ^^ ------------ explicit register argument @@ -77,24 +77,24 @@ LL | asm!("{}", in("x0") foo); | = note: no positional arguments were given note: explicit register arguments cannot be used in the asm template - --> $DIR/bad-template.rs:39:20 + --> $DIR/bad-template.rs:37:20 | LL | asm!("{}", in("x0") foo); | ^^^^^^^^^^^^ help: use the register name directly in the assembly code - --> $DIR/bad-template.rs:39:20 + --> $DIR/bad-template.rs:37:20 | LL | asm!("{}", in("x0") foo); | ^^^^^^^^^^^^ error: asm template modifier must be a single character - --> $DIR/bad-template.rs:41:17 + --> $DIR/bad-template.rs:39:17 | LL | asm!("{:foo}", in(reg) foo); | ^^^ error: multiple unused asm arguments - --> $DIR/bad-template.rs:44:18 + --> $DIR/bad-template.rs:42:18 | LL | asm!("", in(reg) 0, in(reg) 1); | ^^^^^^^^^ ^^^^^^^^^ argument never used @@ -104,7 +104,7 @@ LL | asm!("", in(reg) 0, in(reg) 1); = help: if these arguments are intentionally unused, consider using them in an asm comment: `"/* {0} {1} */"` error: invalid reference to argument at index 0 - --> $DIR/bad-template.rs:50:14 + --> $DIR/bad-template.rs:48:14 | LL | global_asm!("{}"); | ^^ from here @@ -112,7 +112,7 @@ LL | global_asm!("{}"); = note: no arguments were given error: invalid reference to argument at index 1 - --> $DIR/bad-template.rs:52:14 + --> $DIR/bad-template.rs:50:14 | LL | global_asm!("{1}", const FOO); | ^^^ from here @@ -120,7 +120,7 @@ LL | global_asm!("{1}", const FOO); = note: there is 1 argument error: argument never used - --> $DIR/bad-template.rs:52:20 + --> $DIR/bad-template.rs:50:20 | LL | global_asm!("{1}", const FOO); | ^^^^^^^^^ argument never used @@ -128,13 +128,13 @@ LL | global_asm!("{1}", const FOO); = help: if this argument is intentionally unused, consider using it in an asm comment: `"/* {0} */"` error: there is no argument named `a` - --> $DIR/bad-template.rs:55:15 + --> $DIR/bad-template.rs:53:15 | LL | global_asm!("{a}"); | ^ error: invalid reference to argument at index 0 - --> $DIR/bad-template.rs:57:14 + --> $DIR/bad-template.rs:55:14 | LL | global_asm!("{}", a = const FOO); | ^^ ------------- named argument @@ -143,13 +143,13 @@ LL | global_asm!("{}", a = const FOO); | = note: no positional arguments were given note: named arguments cannot be referenced by position - --> $DIR/bad-template.rs:57:19 + --> $DIR/bad-template.rs:55:19 | LL | global_asm!("{}", a = const FOO); | ^^^^^^^^^^^^^ error: named argument never used - --> $DIR/bad-template.rs:57:19 + --> $DIR/bad-template.rs:55:19 | LL | global_asm!("{}", a = const FOO); | ^^^^^^^^^^^^^ named argument never used @@ -157,7 +157,7 @@ LL | global_asm!("{}", a = const FOO); = help: if this argument is intentionally unused, consider using it in an asm comment: `"/* {a} */"` error: invalid reference to argument at index 1 - --> $DIR/bad-template.rs:60:14 + --> $DIR/bad-template.rs:58:14 | LL | global_asm!("{1}", a = const FOO); | ^^^ from here @@ -165,7 +165,7 @@ LL | global_asm!("{1}", a = const FOO); = note: no positional arguments were given error: named argument never used - --> $DIR/bad-template.rs:60:20 + --> $DIR/bad-template.rs:58:20 | LL | global_asm!("{1}", a = const FOO); | ^^^^^^^^^^^^^ named argument never used @@ -173,13 +173,13 @@ LL | global_asm!("{1}", a = const FOO); = help: if this argument is intentionally unused, consider using it in an asm comment: `"/* {a} */"` error: asm template modifier must be a single character - --> $DIR/bad-template.rs:63:16 + --> $DIR/bad-template.rs:61:16 | LL | global_asm!("{:foo}", const FOO); | ^^^ error: multiple unused asm arguments - --> $DIR/bad-template.rs:65:17 + --> $DIR/bad-template.rs:63:17 | LL | global_asm!("", const FOO, const FOO); | ^^^^^^^^^ ^^^^^^^^^ argument never used @@ -189,7 +189,7 @@ LL | global_asm!("", const FOO, const FOO); = help: if these arguments are intentionally unused, consider using them in an asm comment: `"/* {0} {1} */"` warning: formatting may not be suitable for sub-register argument - --> $DIR/bad-template.rs:41:15 + --> $DIR/bad-template.rs:39:15 | LL | asm!("{:foo}", in(reg) foo); | ^^^^^^ --- for this argument diff --git a/tests/ui/asm/bad-template.rs b/tests/ui/asm/bad-template.rs index 51fae14f54d0f..367cd476f8edd 100644 --- a/tests/ui/asm/bad-template.rs +++ b/tests/ui/asm/bad-template.rs @@ -1,7 +1,5 @@ //@ add-minicore //@ revisions: x86_64 aarch64 -//@ reference: asm.ts-args.at-least-once -//@ reference: asm.template-modifiers.only-one //@ [x86_64] compile-flags: --target x86_64-unknown-linux-gnu //@ [aarch64] compile-flags: --target aarch64-unknown-linux-gnu @@ -64,3 +62,9 @@ global_asm!("{:foo}", const FOO); //~^ ERROR asm template modifier must be a single character global_asm!("", const FOO, const FOO); //~^ ERROR multiple unused asm arguments + +//@ reference: asm.template-modifiers.only-one +//@ reference: asm.ts-args.at-least-once +//@ reference: asm.ts-args.no-implicit +//@ reference: asm.ts-args.order +//@ reference: asm.ts-args.register-operands diff --git a/tests/ui/asm/bad-template.x86_64.stderr b/tests/ui/asm/bad-template.x86_64.stderr index cc8626deeb5fa..fffddafdd805c 100644 --- a/tests/ui/asm/bad-template.x86_64.stderr +++ b/tests/ui/asm/bad-template.x86_64.stderr @@ -1,5 +1,5 @@ error: invalid reference to argument at index 0 - --> $DIR/bad-template.rs:22:15 + --> $DIR/bad-template.rs:20:15 | LL | asm!("{}"); | ^^ from here @@ -7,7 +7,7 @@ LL | asm!("{}"); = note: no arguments were given error: invalid reference to argument at index 1 - --> $DIR/bad-template.rs:24:15 + --> $DIR/bad-template.rs:22:15 | LL | asm!("{1}", in(reg) foo); | ^^^ from here @@ -15,7 +15,7 @@ LL | asm!("{1}", in(reg) foo); = note: there is 1 argument error: argument never used - --> $DIR/bad-template.rs:24:21 + --> $DIR/bad-template.rs:22:21 | LL | asm!("{1}", in(reg) foo); | ^^^^^^^^^^^ argument never used @@ -23,13 +23,13 @@ LL | asm!("{1}", in(reg) foo); = help: if this argument is intentionally unused, consider using it in an asm comment: `"/* {0} */"` error: there is no argument named `a` - --> $DIR/bad-template.rs:27:16 + --> $DIR/bad-template.rs:25:16 | LL | asm!("{a}"); | ^ error: invalid reference to argument at index 0 - --> $DIR/bad-template.rs:29:15 + --> $DIR/bad-template.rs:27:15 | LL | asm!("{}", a = in(reg) foo); | ^^ --------------- named argument @@ -38,13 +38,13 @@ LL | asm!("{}", a = in(reg) foo); | = note: no positional arguments were given note: named arguments cannot be referenced by position - --> $DIR/bad-template.rs:29:20 + --> $DIR/bad-template.rs:27:20 | LL | asm!("{}", a = in(reg) foo); | ^^^^^^^^^^^^^^^ error: named argument never used - --> $DIR/bad-template.rs:29:20 + --> $DIR/bad-template.rs:27:20 | LL | asm!("{}", a = in(reg) foo); | ^^^^^^^^^^^^^^^ named argument never used @@ -52,7 +52,7 @@ LL | asm!("{}", a = in(reg) foo); = help: if this argument is intentionally unused, consider using it in an asm comment: `"/* {a} */"` error: invalid reference to argument at index 1 - --> $DIR/bad-template.rs:32:15 + --> $DIR/bad-template.rs:30:15 | LL | asm!("{1}", a = in(reg) foo); | ^^^ from here @@ -60,7 +60,7 @@ LL | asm!("{1}", a = in(reg) foo); = note: no positional arguments were given error: named argument never used - --> $DIR/bad-template.rs:32:21 + --> $DIR/bad-template.rs:30:21 | LL | asm!("{1}", a = in(reg) foo); | ^^^^^^^^^^^^^^^ named argument never used @@ -68,7 +68,7 @@ LL | asm!("{1}", a = in(reg) foo); = help: if this argument is intentionally unused, consider using it in an asm comment: `"/* {a} */"` error: invalid reference to argument at index 0 - --> $DIR/bad-template.rs:36:15 + --> $DIR/bad-template.rs:34:15 | LL | asm!("{}", in("eax") foo); | ^^ ------------- explicit register argument @@ -77,24 +77,24 @@ LL | asm!("{}", in("eax") foo); | = note: no positional arguments were given note: explicit register arguments cannot be used in the asm template - --> $DIR/bad-template.rs:36:20 + --> $DIR/bad-template.rs:34:20 | LL | asm!("{}", in("eax") foo); | ^^^^^^^^^^^^^ help: use the register name directly in the assembly code - --> $DIR/bad-template.rs:36:20 + --> $DIR/bad-template.rs:34:20 | LL | asm!("{}", in("eax") foo); | ^^^^^^^^^^^^^ error: asm template modifier must be a single character - --> $DIR/bad-template.rs:41:17 + --> $DIR/bad-template.rs:39:17 | LL | asm!("{:foo}", in(reg) foo); | ^^^ error: multiple unused asm arguments - --> $DIR/bad-template.rs:44:18 + --> $DIR/bad-template.rs:42:18 | LL | asm!("", in(reg) 0, in(reg) 1); | ^^^^^^^^^ ^^^^^^^^^ argument never used @@ -104,7 +104,7 @@ LL | asm!("", in(reg) 0, in(reg) 1); = help: if these arguments are intentionally unused, consider using them in an asm comment: `"/* {0} {1} */"` error: invalid reference to argument at index 0 - --> $DIR/bad-template.rs:50:14 + --> $DIR/bad-template.rs:48:14 | LL | global_asm!("{}"); | ^^ from here @@ -112,7 +112,7 @@ LL | global_asm!("{}"); = note: no arguments were given error: invalid reference to argument at index 1 - --> $DIR/bad-template.rs:52:14 + --> $DIR/bad-template.rs:50:14 | LL | global_asm!("{1}", const FOO); | ^^^ from here @@ -120,7 +120,7 @@ LL | global_asm!("{1}", const FOO); = note: there is 1 argument error: argument never used - --> $DIR/bad-template.rs:52:20 + --> $DIR/bad-template.rs:50:20 | LL | global_asm!("{1}", const FOO); | ^^^^^^^^^ argument never used @@ -128,13 +128,13 @@ LL | global_asm!("{1}", const FOO); = help: if this argument is intentionally unused, consider using it in an asm comment: `"/* {0} */"` error: there is no argument named `a` - --> $DIR/bad-template.rs:55:15 + --> $DIR/bad-template.rs:53:15 | LL | global_asm!("{a}"); | ^ error: invalid reference to argument at index 0 - --> $DIR/bad-template.rs:57:14 + --> $DIR/bad-template.rs:55:14 | LL | global_asm!("{}", a = const FOO); | ^^ ------------- named argument @@ -143,13 +143,13 @@ LL | global_asm!("{}", a = const FOO); | = note: no positional arguments were given note: named arguments cannot be referenced by position - --> $DIR/bad-template.rs:57:19 + --> $DIR/bad-template.rs:55:19 | LL | global_asm!("{}", a = const FOO); | ^^^^^^^^^^^^^ error: named argument never used - --> $DIR/bad-template.rs:57:19 + --> $DIR/bad-template.rs:55:19 | LL | global_asm!("{}", a = const FOO); | ^^^^^^^^^^^^^ named argument never used @@ -157,7 +157,7 @@ LL | global_asm!("{}", a = const FOO); = help: if this argument is intentionally unused, consider using it in an asm comment: `"/* {a} */"` error: invalid reference to argument at index 1 - --> $DIR/bad-template.rs:60:14 + --> $DIR/bad-template.rs:58:14 | LL | global_asm!("{1}", a = const FOO); | ^^^ from here @@ -165,7 +165,7 @@ LL | global_asm!("{1}", a = const FOO); = note: no positional arguments were given error: named argument never used - --> $DIR/bad-template.rs:60:20 + --> $DIR/bad-template.rs:58:20 | LL | global_asm!("{1}", a = const FOO); | ^^^^^^^^^^^^^ named argument never used @@ -173,13 +173,13 @@ LL | global_asm!("{1}", a = const FOO); = help: if this argument is intentionally unused, consider using it in an asm comment: `"/* {a} */"` error: asm template modifier must be a single character - --> $DIR/bad-template.rs:63:16 + --> $DIR/bad-template.rs:61:16 | LL | global_asm!("{:foo}", const FOO); | ^^^ error: multiple unused asm arguments - --> $DIR/bad-template.rs:65:17 + --> $DIR/bad-template.rs:63:17 | LL | global_asm!("", const FOO, const FOO); | ^^^^^^^^^ ^^^^^^^^^ argument never used @@ -189,7 +189,7 @@ LL | global_asm!("", const FOO, const FOO); = help: if these arguments are intentionally unused, consider using them in an asm comment: `"/* {0} {1} */"` warning: formatting may not be suitable for sub-register argument - --> $DIR/bad-template.rs:41:15 + --> $DIR/bad-template.rs:39:15 | LL | asm!("{:foo}", in(reg) foo); | ^^^^^^ --- for this argument diff --git a/tests/ui/asm/cfg-parse-error.rs b/tests/ui/asm/cfg-parse-error.rs index c13d003cbcebc..1ae932adfbab2 100644 --- a/tests/ui/asm/cfg-parse-error.rs +++ b/tests/ui/asm/cfg-parse-error.rs @@ -1,5 +1,4 @@ //@ needs-asm-support -//@ reference: asm.attributes.supported-attributes use std::arch::asm; @@ -55,3 +54,6 @@ fn main() { ); } } + +//@ reference: asm.attributes.starts-with-template +//@ reference: asm.attributes.supported-attributes diff --git a/tests/ui/asm/cfg-parse-error.stderr b/tests/ui/asm/cfg-parse-error.stderr index 8a70d39a43dc6..726dee271108f 100644 --- a/tests/ui/asm/cfg-parse-error.stderr +++ b/tests/ui/asm/cfg-parse-error.stderr @@ -1,5 +1,5 @@ error: expected one of `#`, `clobber_abi`, `const`, `in`, `inlateout`, `inout`, `label`, `lateout`, `options`, `out`, or `sym`, found `""` - --> $DIR/cfg-parse-error.rs:16:13 + --> $DIR/cfg-parse-error.rs:15:13 | LL | a = out(reg) x, | - expected one of 11 possible tokens @@ -7,7 +7,7 @@ LL | "", | ^^ unexpected token error: expected one of `#`, `clobber_abi`, `const`, `in`, `inlateout`, `inout`, `label`, `lateout`, `options`, `out`, or `sym`, found `""` - --> $DIR/cfg-parse-error.rs:26:13 + --> $DIR/cfg-parse-error.rs:25:13 | LL | }, | - expected one of 11 possible tokens @@ -15,19 +15,19 @@ LL | "", | ^^ unexpected token error: expected token: `,` - --> $DIR/cfg-parse-error.rs:41:26 + --> $DIR/cfg-parse-error.rs:40:26 | LL | a = out(reg) x, | ^ expected `,` error: this attribute is not supported on assembly - --> $DIR/cfg-parse-error.rs:47:13 + --> $DIR/cfg-parse-error.rs:46:13 | LL | #[rustfmt::skip] | ^^^^^^^^^^^^^^^^ error: an inner attribute is not permitted in this context - --> $DIR/cfg-parse-error.rs:53:13 + --> $DIR/cfg-parse-error.rs:52:13 | LL | #![rustfmt::skip] | ^^^^^^^^^^^^^^^^^ diff --git a/tests/ui/asm/conditionally-sized-ptr-fail.rs b/tests/ui/asm/conditionally-sized-ptr-fail.rs index b0a93495ffafe..0bb8043126c5c 100644 --- a/tests/ui/asm/conditionally-sized-ptr-fail.rs +++ b/tests/ui/asm/conditionally-sized-ptr-fail.rs @@ -17,3 +17,5 @@ fn _g(p: *mut [u8]) { } fn main() {} + +//@ reference: asm.register-operands.allowed-types diff --git a/tests/ui/asm/conditionally-sized-ptr.rs b/tests/ui/asm/conditionally-sized-ptr.rs index 8ff18fd1da165..b23e9f9893e23 100644 --- a/tests/ui/asm/conditionally-sized-ptr.rs +++ b/tests/ui/asm/conditionally-sized-ptr.rs @@ -10,3 +10,5 @@ fn _f(p: *mut T) { } fn main() {} + +//@ reference: asm.register-operands.allowed-types diff --git a/tests/ui/asm/global-asm-mono-sym-fn.rs b/tests/ui/asm/global-asm-mono-sym-fn.rs index e584a98badb0d..2ba9db808e9f4 100644 --- a/tests/ui/asm/global-asm-mono-sym-fn.rs +++ b/tests/ui/asm/global-asm-mono-sym-fn.rs @@ -25,3 +25,5 @@ impl Foo for i32 { } global_asm!(".global main", "main:", "call {}", sym ::bar); + +//@ reference: asm.operand-type.supported-operands-sym diff --git a/tests/ui/asm/ice-bad-err-span-in-template-129503.rs b/tests/ui/asm/ice-bad-err-span-in-template-129503.rs index 0a7d0d405d17d..00b4d9070e2eb 100644 --- a/tests/ui/asm/ice-bad-err-span-in-template-129503.rs +++ b/tests/ui/asm/ice-bad-err-span-in-template-129503.rs @@ -29,3 +29,5 @@ fn main() { asm!("abc", "r} {}"); //~^ ERROR invalid asm template string: unmatched `}` found } + +//@ reference: asm.ts-args.syntax diff --git a/tests/ui/asm/inline-syntax.rs b/tests/ui/asm/inline-syntax.rs index d7c9fc8972cb7..16e2c19e43949 100644 --- a/tests/ui/asm/inline-syntax.rs +++ b/tests/ui/asm/inline-syntax.rs @@ -49,3 +49,6 @@ global_asm!(".intel_syntax noprefix", "nop"); // Global assembly errors don't have line numbers, so no error on ARM. //[arm]~? ERROR unknown directive + +//@ reference: asm.directives.subset-supported +//@ reference: asm.ts-args.llvm-syntax diff --git a/tests/ui/asm/issue-85247.rs b/tests/ui/asm/issue-85247.rs index ff44f8763f744..5cf2865c0b790 100644 --- a/tests/ui/asm/issue-85247.rs +++ b/tests/ui/asm/issue-85247.rs @@ -22,3 +22,5 @@ fn main() { //[rwpi]~^ ERROR cannot use register `r9` } } + +//@ reference: asm.register-names.not-for-io diff --git a/tests/ui/asm/issue-92378.rs b/tests/ui/asm/issue-92378.rs index 7a41ed5993aea..862de36dc17af 100644 --- a/tests/ui/asm/issue-92378.rs +++ b/tests/ui/asm/issue-92378.rs @@ -25,3 +25,5 @@ pub fn thumb() { asm!("", out("r11") _); } } + +//@ reference: asm.register-names.not-for-io diff --git a/tests/ui/asm/issue-99071.rs b/tests/ui/asm/issue-99071.rs index 1404b37307082..ea7cac4dbfefb 100644 --- a/tests/ui/asm/issue-99071.rs +++ b/tests/ui/asm/issue-99071.rs @@ -16,3 +16,5 @@ pub fn foo() { //~^ ERROR cannot use register `r8`: high registers (r8+) can only be used as clobbers in Thumb-1 code } } + +//@ reference: asm.register-operands.supported-register-classes diff --git a/tests/ui/asm/loongarch/bad-reg.rs b/tests/ui/asm/loongarch/bad-reg.rs index ac2eeb7d78a70..5d9ade2b64954 100644 --- a/tests/ui/asm/loongarch/bad-reg.rs +++ b/tests/ui/asm/loongarch/bad-reg.rs @@ -99,3 +99,9 @@ fn f() { //[loongarch64_lp64d]~^^^^^ ERROR register `$xr0` conflicts with register `$vr0` } } + +//@ reference: asm.register-names.not-for-io +//@ reference: asm.register-names.supported-register-aliases +//@ reference: asm.register-operands.error-overlapping +//@ reference: asm.register-operands.supported-register-classes +//@ reference: asm.register-operands.value-type-constraints diff --git a/tests/ui/asm/naked-functions/mono-sym-fn.rs b/tests/ui/asm/naked-functions/mono-sym-fn.rs index 948c290c0b4fb..d941fd6d391b7 100644 --- a/tests/ui/asm/naked-functions/mono-sym-fn.rs +++ b/tests/ui/asm/naked-functions/mono-sym-fn.rs @@ -33,3 +33,5 @@ extern "C" fn foo() { fn main() { foo::>(); } + +//@ reference: asm.operand-type.supported-operands-sym diff --git a/tests/ui/asm/naked-functions/naked-functions.rs b/tests/ui/asm/naked-functions/naked-functions.rs index e7da65a169074..12f777e959e4f 100644 --- a/tests/ui/asm/naked-functions/naked-functions.rs +++ b/tests/ui/asm/naked-functions/naked-functions.rs @@ -1,7 +1,6 @@ //@ needs-asm-support //@ ignore-nvptx64 //@ ignore-spirv -//@ reference: attributes.codegen.naked.body #![feature(asm_unwind, linkage, rustc_attrs, cfg_target_object_format)] #![crate_type = "lib"] @@ -248,3 +247,7 @@ pub extern "C" fn rustfmt_skip() { unsafe extern "custom" fn abi_custom() { naked_asm!("") } + +//@ reference: asm.operand-type.naked_asm-restriction +//@ reference: asm.options.naked_asm-restriction +//@ reference: attributes.codegen.naked.body diff --git a/tests/ui/asm/naked-functions/naked-functions.stderr b/tests/ui/asm/naked-functions/naked-functions.stderr index 2b67c3aecd73c..b94a09bb92ed9 100644 --- a/tests/ui/asm/naked-functions/naked-functions.stderr +++ b/tests/ui/asm/naked-functions/naked-functions.stderr @@ -1,107 +1,107 @@ error: the `in` operand cannot be used with `naked_asm!` - --> $DIR/naked-functions.rs:47:29 + --> $DIR/naked-functions.rs:46:29 | LL | naked_asm!("/* {0} */", in(reg) a) | ^^ the `in` operand is not meaningful for global-scoped inline assembly, remove it error: the `in` operand cannot be used with `naked_asm!` - --> $DIR/naked-functions.rs:68:10 + --> $DIR/naked-functions.rs:67:10 | LL | in(reg) a, | ^^ the `in` operand is not meaningful for global-scoped inline assembly, remove it error: the `noreturn` option cannot be used with `naked_asm!` - --> $DIR/naked-functions.rs:88:28 + --> $DIR/naked-functions.rs:87:28 | LL | naked_asm!("", options(noreturn)); | ^^^^^^^^ the `noreturn` option is not meaningful for global-scoped inline assembly error: the `nomem` option cannot be used with `naked_asm!` - --> $DIR/naked-functions.rs:105:28 + --> $DIR/naked-functions.rs:104:28 | LL | naked_asm!("", options(nomem, preserves_flags)); | ^^^^^ the `nomem` option is not meaningful for global-scoped inline assembly error: the `preserves_flags` option cannot be used with `naked_asm!` - --> $DIR/naked-functions.rs:105:35 + --> $DIR/naked-functions.rs:104:35 | LL | naked_asm!("", options(nomem, preserves_flags)); | ^^^^^^^^^^^^^^^ the `preserves_flags` option is not meaningful for global-scoped inline assembly error: the `readonly` option cannot be used with `naked_asm!` - --> $DIR/naked-functions.rs:112:28 + --> $DIR/naked-functions.rs:111:28 | LL | naked_asm!("", options(readonly, nostack), options(pure)); | ^^^^^^^^ the `readonly` option is not meaningful for global-scoped inline assembly error: the `nostack` option cannot be used with `naked_asm!` - --> $DIR/naked-functions.rs:112:38 + --> $DIR/naked-functions.rs:111:38 | LL | naked_asm!("", options(readonly, nostack), options(pure)); | ^^^^^^^ the `nostack` option is not meaningful for global-scoped inline assembly error: the `pure` option cannot be used with `naked_asm!` - --> $DIR/naked-functions.rs:112:56 + --> $DIR/naked-functions.rs:111:56 | LL | naked_asm!("", options(readonly, nostack), options(pure)); | ^^^^ the `pure` option is not meaningful for global-scoped inline assembly error: the `may_unwind` option cannot be used with `naked_asm!` - --> $DIR/naked-functions.rs:120:28 + --> $DIR/naked-functions.rs:119:28 | LL | naked_asm!("", options(may_unwind)); | ^^^^^^^^^^ the `may_unwind` option is not meaningful for global-scoped inline assembly error: this is a user specified error - --> $DIR/naked-functions.rs:151:5 + --> $DIR/naked-functions.rs:150:5 | LL | compile_error!("this is a user specified error") | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ error: this is a user specified error - --> $DIR/naked-functions.rs:157:5 + --> $DIR/naked-functions.rs:156:5 | LL | compile_error!("this is a user specified error"); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ error: asm template must be a string literal - --> $DIR/naked-functions.rs:164:16 + --> $DIR/naked-functions.rs:163:16 | LL | naked_asm!(invalid_syntax) | ^^^^^^^^^^^^^^ error[E0787]: the `asm!` macro is not allowed in naked functions - --> $DIR/naked-functions.rs:13:14 + --> $DIR/naked-functions.rs:12:14 | LL | unsafe { asm!("", options(raw)) }; | ^^^^^^^^^^^^^^^^^^^^^^ consider using the `naked_asm!` macro instead error: patterns not allowed in naked function parameters - --> $DIR/naked-functions.rs:25:5 + --> $DIR/naked-functions.rs:24:5 | LL | mut a: u32, | ^^^^^ error: patterns not allowed in naked function parameters - --> $DIR/naked-functions.rs:27:5 + --> $DIR/naked-functions.rs:26:5 | LL | &b: &i32, | ^^ error: patterns not allowed in naked function parameters - --> $DIR/naked-functions.rs:29:6 + --> $DIR/naked-functions.rs:28:6 | LL | (None | Some(_)): Option>, | ^^^^^^^^^^^^^^ error: patterns not allowed in naked function parameters - --> $DIR/naked-functions.rs:31:5 + --> $DIR/naked-functions.rs:30:5 | LL | P { x, y }: P, | ^^^^^^^^^^ error: referencing function parameters is not allowed in naked functions - --> $DIR/naked-functions.rs:40:5 + --> $DIR/naked-functions.rs:39:5 | LL | a + 1 | ^ @@ -109,7 +109,7 @@ LL | a + 1 = help: follow the calling convention in asm block to use parameters error[E0787]: naked functions must contain a single `naked_asm!` invocation - --> $DIR/naked-functions.rs:38:1 + --> $DIR/naked-functions.rs:37:1 | LL | pub extern "C" fn inc(a: u32) -> u32 { | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ @@ -118,7 +118,7 @@ LL | a + 1 | ----- not allowed in naked functions error[E0787]: naked functions must contain a single `naked_asm!` invocation - --> $DIR/naked-functions.rs:52:1 + --> $DIR/naked-functions.rs:51:1 | LL | pub extern "C" fn inc_closure(a: u32) -> u32 { | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ @@ -127,7 +127,7 @@ LL | (|| a + 1)() | ------------ not allowed in naked functions error[E0787]: naked functions must contain a single `naked_asm!` invocation - --> $DIR/naked-functions.rs:58:1 + --> $DIR/naked-functions.rs:57:1 | LL | pub extern "C" fn unsupported_operands() { | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ @@ -144,13 +144,13 @@ LL | let mut e = 0usize; | ------------------- not allowed in naked functions error[E0787]: naked functions must contain a single `naked_asm!` invocation - --> $DIR/naked-functions.rs:80:1 + --> $DIR/naked-functions.rs:79:1 | LL | pub extern "C" fn missing_assembly() { | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ error[E0787]: naked functions must contain a single `naked_asm!` invocation - --> $DIR/naked-functions.rs:85:1 + --> $DIR/naked-functions.rs:84:1 | LL | pub extern "C" fn too_many_asm_blocks() { | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ @@ -159,7 +159,7 @@ LL | naked_asm!(""); | -------------- multiple `naked_asm!` invocations are not allowed in naked functions error: referencing function parameters is not allowed in naked functions - --> $DIR/naked-functions.rs:97:11 + --> $DIR/naked-functions.rs:96:11 | LL | *&y | ^ @@ -167,7 +167,7 @@ LL | *&y = help: follow the calling convention in asm block to use parameters error[E0787]: naked functions must contain a single `naked_asm!` invocation - --> $DIR/naked-functions.rs:95:5 + --> $DIR/naked-functions.rs:94:5 | LL | pub extern "C" fn inner(y: usize) -> usize { | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ diff --git a/tests/ui/asm/named-asm-labels.rs b/tests/ui/asm/named-asm-labels.rs index e78553fd775f0..fbcba3f2a759e 100644 --- a/tests/ui/asm/named-asm-labels.rs +++ b/tests/ui/asm/named-asm-labels.rs @@ -246,3 +246,5 @@ trait Foo { naked_asm!(".Lbbb: nop; ret;") //~ ERROR avoid using named labels } } + +//@ reference: asm.rules.not-exactly-once diff --git a/tests/ui/asm/parse-error.rs b/tests/ui/asm/parse-error.rs index f8e3b1622a8bc..364101b375d78 100644 --- a/tests/ui/asm/parse-error.rs +++ b/tests/ui/asm/parse-error.rs @@ -1,7 +1,4 @@ //@ needs-asm-support -//@ reference: asm.syntax -//@ reference: asm.ts-args.syntax -//@ reference: asm.ts-args.one-or-more use std::arch::{asm, global_asm}; @@ -158,3 +155,10 @@ global_asm!("{}", inlateout(reg)); //~^ ERROR the `inlateout` operand cannot be used with `global_asm!` global_asm!("{}", label(reg)); //~^ ERROR the `label` operand cannot be used with `global_asm!` + +//@ reference: asm.operand-type.global_asm-restriction +//@ reference: asm.options.global_asm-restriction +//@ reference: asm.syntax +//@ reference: asm.ts-args.before-other-args +//@ reference: asm.ts-args.one-or-more +//@ reference: asm.ts-args.syntax diff --git a/tests/ui/asm/parse-error.stderr b/tests/ui/asm/parse-error.stderr index 0048fa5075db2..1b3d12c1b7959 100644 --- a/tests/ui/asm/parse-error.stderr +++ b/tests/ui/asm/parse-error.stderr @@ -1,59 +1,59 @@ error: requires at least a template string argument - --> $DIR/parse-error.rs:12:9 + --> $DIR/parse-error.rs:9:9 | LL | asm!(); | ^^^^^^ error: asm template must be a string literal - --> $DIR/parse-error.rs:14:14 + --> $DIR/parse-error.rs:11:14 | LL | asm!(foo); | ^^^ error: expected token: `,` - --> $DIR/parse-error.rs:16:19 + --> $DIR/parse-error.rs:13:19 | LL | asm!("{}" foo); | ^^^ expected `,` error: expected operand, clobber_abi, options, or additional template string - --> $DIR/parse-error.rs:18:20 + --> $DIR/parse-error.rs:15:20 | LL | asm!("{}", foo); | ^^^ expected operand, clobber_abi, options, or additional template string error: expected `(`, found `foo` - --> $DIR/parse-error.rs:20:23 + --> $DIR/parse-error.rs:17:23 | LL | asm!("{}", in foo); | ^^^ expected `(` error: expected `)`, found `foo` - --> $DIR/parse-error.rs:22:27 + --> $DIR/parse-error.rs:19:27 | LL | asm!("{}", in(reg foo)); | ^^^ expected `)` error: expected expression, found end of macro arguments - --> $DIR/parse-error.rs:24:27 + --> $DIR/parse-error.rs:21:27 | LL | asm!("{}", in(reg)); | ^ expected expression error: expected register class or explicit register - --> $DIR/parse-error.rs:26:26 + --> $DIR/parse-error.rs:23:26 | LL | asm!("{}", inout(=) foo => bar); | ^ error: expected expression, found end of macro arguments - --> $DIR/parse-error.rs:28:37 + --> $DIR/parse-error.rs:25:37 | LL | asm!("{}", inout(reg) foo =>); | ^ expected expression error: expected one of `!`, `,`, `.`, `::`, `?`, `{`, or an operator, found `=>` - --> $DIR/parse-error.rs:30:32 + --> $DIR/parse-error.rs:27:32 | LL | asm!("{}", in(reg) foo => bar); | ^^ expected one of 7 possible tokens @@ -65,109 +65,109 @@ LL + asm!("{}", in(reg) foo >= bar); | error: expected a path for argument to `sym` - --> $DIR/parse-error.rs:32:24 + --> $DIR/parse-error.rs:29:24 | LL | asm!("{}", sym foo + bar); | ^^^^^^^^^ error: expected one of `)`, `att_syntax`, `may_unwind`, `nomem`, `noreturn`, `nostack`, `preserves_flags`, `pure`, `raw`, or `readonly`, found `foo` - --> $DIR/parse-error.rs:34:26 + --> $DIR/parse-error.rs:31:26 | LL | asm!("", options(foo)); | ^^^ expected one of 10 possible tokens error: expected one of `)` or `,`, found `foo` - --> $DIR/parse-error.rs:36:32 + --> $DIR/parse-error.rs:33:32 | LL | asm!("", options(nomem foo)); | ^^^ expected one of `)` or `,` error: expected one of `)`, `att_syntax`, `may_unwind`, `nomem`, `noreturn`, `nostack`, `preserves_flags`, `pure`, `raw`, or `readonly`, found `foo` - --> $DIR/parse-error.rs:38:33 + --> $DIR/parse-error.rs:35:33 | LL | asm!("", options(nomem, foo)); | ^^^ expected one of 10 possible tokens error: at least one abi must be provided as an argument to `clobber_abi` - --> $DIR/parse-error.rs:45:30 + --> $DIR/parse-error.rs:42:30 | LL | asm!("", clobber_abi()); | ^ error: expected string literal - --> $DIR/parse-error.rs:47:30 + --> $DIR/parse-error.rs:44:30 | LL | asm!("", clobber_abi(foo)); | ^^^ not a string literal error: expected one of `)` or `,`, found `foo` - --> $DIR/parse-error.rs:49:34 + --> $DIR/parse-error.rs:46:34 | LL | asm!("", clobber_abi("C" foo)); | ^^^ expected one of `)` or `,` error: expected string literal - --> $DIR/parse-error.rs:51:35 + --> $DIR/parse-error.rs:48:35 | LL | asm!("", clobber_abi("C", foo)); | ^^^ not a string literal error: expected string literal - --> $DIR/parse-error.rs:53:30 + --> $DIR/parse-error.rs:50:30 | LL | asm!("", clobber_abi(1)); | ^ not a string literal error: expected string literal - --> $DIR/parse-error.rs:55:30 + --> $DIR/parse-error.rs:52:30 | LL | asm!("", clobber_abi(())); | ^ not a string literal error: expected string literal - --> $DIR/parse-error.rs:57:30 + --> $DIR/parse-error.rs:54:30 | LL | asm!("", clobber_abi(uwu)); | ^^^ not a string literal error: expected string literal - --> $DIR/parse-error.rs:59:30 + --> $DIR/parse-error.rs:56:30 | LL | asm!("", clobber_abi({})); | ^ not a string literal error: expected string literal - --> $DIR/parse-error.rs:61:30 + --> $DIR/parse-error.rs:58:30 | LL | asm!("", clobber_abi(loop {})); | ^^^^ not a string literal error: expected string literal - --> $DIR/parse-error.rs:63:30 + --> $DIR/parse-error.rs:60:30 | LL | asm!("", clobber_abi(if)); | ^^ not a string literal error: expected string literal - --> $DIR/parse-error.rs:65:30 + --> $DIR/parse-error.rs:62:30 | LL | asm!("", clobber_abi(do)); | ^^ not a string literal error: expected string literal - --> $DIR/parse-error.rs:67:30 + --> $DIR/parse-error.rs:64:30 | LL | asm!("", clobber_abi(<)); | ^ not a string literal error: expected string literal - --> $DIR/parse-error.rs:69:30 + --> $DIR/parse-error.rs:66:30 | LL | asm!("", clobber_abi(.)); | ^ not a string literal error: duplicate argument named `a` - --> $DIR/parse-error.rs:77:36 + --> $DIR/parse-error.rs:74:36 | LL | asm!("{a}", a = const foo, a = const bar); | ------------- ^^^^^^^^^^^^^ duplicate argument @@ -175,7 +175,7 @@ LL | asm!("{a}", a = const foo, a = const bar); | previously here error: argument never used - --> $DIR/parse-error.rs:77:36 + --> $DIR/parse-error.rs:74:36 | LL | asm!("{a}", a = const foo, a = const bar); | ^^^^^^^^^^^^^ argument never used @@ -183,151 +183,151 @@ LL | asm!("{a}", a = const foo, a = const bar); = help: if this argument is intentionally unused, consider using it in an asm comment: `"/* {1} */"` error: expected one of `#`, `clobber_abi`, `const`, `in`, `inlateout`, `inout`, `label`, `lateout`, `options`, `out`, or `sym`, found `""` - --> $DIR/parse-error.rs:83:29 + --> $DIR/parse-error.rs:80:29 | LL | asm!("", options(), ""); | ^^ expected one of 11 possible tokens error: expected one of `#`, `clobber_abi`, `const`, `in`, `inlateout`, `inout`, `label`, `lateout`, `options`, `out`, or `sym`, found `"{}"` - --> $DIR/parse-error.rs:85:33 + --> $DIR/parse-error.rs:82:33 | LL | asm!("{}", in(reg) foo, "{}", out(reg) foo); | ^^^^ expected one of 11 possible tokens error: asm template must be a string literal - --> $DIR/parse-error.rs:87:14 + --> $DIR/parse-error.rs:84:14 | LL | asm!(format!("{{{}}}", 0), in(reg) foo); | ^^^^^^^^^^^^^^^^^^^^ error: asm template must be a string literal - --> $DIR/parse-error.rs:89:21 + --> $DIR/parse-error.rs:86:21 | LL | asm!("{1}", format!("{{{}}}", 0), in(reg) foo, out(reg) bar); | ^^^^^^^^^^^^^^^^^^^^ error: _ cannot be used for input operands - --> $DIR/parse-error.rs:91:28 + --> $DIR/parse-error.rs:88:28 | LL | asm!("{}", in(reg) _); | ^ error: _ cannot be used for input operands - --> $DIR/parse-error.rs:93:31 + --> $DIR/parse-error.rs:90:31 | LL | asm!("{}", inout(reg) _); | ^ error: _ cannot be used for input operands - --> $DIR/parse-error.rs:95:35 + --> $DIR/parse-error.rs:92:35 | LL | asm!("{}", inlateout(reg) _); | ^ error: requires at least a template string argument - --> $DIR/parse-error.rs:102:1 + --> $DIR/parse-error.rs:99:1 | LL | global_asm!(); | ^^^^^^^^^^^^^ error: asm template must be a string literal - --> $DIR/parse-error.rs:104:13 + --> $DIR/parse-error.rs:101:13 | LL | global_asm!(FOO); | ^^^ error: expected token: `,` - --> $DIR/parse-error.rs:106:18 + --> $DIR/parse-error.rs:103:18 | LL | global_asm!("{}" FOO); | ^^^ expected `,` error: expected operand, options, or additional template string - --> $DIR/parse-error.rs:108:19 + --> $DIR/parse-error.rs:105:19 | LL | global_asm!("{}", FOO); | ^^^ expected operand, options, or additional template string error: expected expression, found end of macro arguments - --> $DIR/parse-error.rs:110:24 + --> $DIR/parse-error.rs:107:24 | LL | global_asm!("{}", const); | ^ expected expression error: expected one of `,`, `.`, `?`, or an operator, found `FOO` - --> $DIR/parse-error.rs:112:30 + --> $DIR/parse-error.rs:109:30 | LL | global_asm!("{}", const(reg) FOO); | ^^^ expected one of `,`, `.`, `?`, or an operator error: expected one of `)`, `att_syntax`, or `raw`, found `FOO` - --> $DIR/parse-error.rs:114:25 + --> $DIR/parse-error.rs:111:25 | LL | global_asm!("", options(FOO)); | ^^^ expected one of `)`, `att_syntax`, or `raw` error: expected one of `)`, `att_syntax`, or `raw`, found `FOO` - --> $DIR/parse-error.rs:116:25 + --> $DIR/parse-error.rs:113:25 | LL | global_asm!("", options(FOO,)); | ^^^ expected one of `)`, `att_syntax`, or `raw` error: expected one of `)` or `,`, found `FOO` - --> $DIR/parse-error.rs:118:31 + --> $DIR/parse-error.rs:115:31 | LL | global_asm!("", options(nomem FOO)); | ^^^ expected one of `)` or `,` error: expected one of `)`, `att_syntax`, or `raw`, found `FOO` - --> $DIR/parse-error.rs:120:32 + --> $DIR/parse-error.rs:117:32 | LL | global_asm!("", options(nomem, FOO)); | ^^^ expected one of `)`, `att_syntax`, or `raw` error: expected string literal - --> $DIR/parse-error.rs:123:29 + --> $DIR/parse-error.rs:120:29 | LL | global_asm!("", clobber_abi(FOO)); | ^^^ not a string literal error: expected one of `)` or `,`, found `FOO` - --> $DIR/parse-error.rs:125:33 + --> $DIR/parse-error.rs:122:33 | LL | global_asm!("", clobber_abi("C" FOO)); | ^^^ expected one of `)` or `,` error: expected string literal - --> $DIR/parse-error.rs:127:34 + --> $DIR/parse-error.rs:124:34 | LL | global_asm!("", clobber_abi("C", FOO)); | ^^^ not a string literal error: `clobber_abi` cannot be used with `global_asm!` - --> $DIR/parse-error.rs:129:19 + --> $DIR/parse-error.rs:126:19 | LL | global_asm!("{}", clobber_abi("C"), const FOO); | ^^^^^^^^^^^^^^^^ error: `clobber_abi` cannot be used with `global_asm!` - --> $DIR/parse-error.rs:131:28 + --> $DIR/parse-error.rs:128:28 | LL | global_asm!("", options(), clobber_abi("C")); | ^^^^^^^^^^^^^^^^ error: `clobber_abi` cannot be used with `global_asm!` - --> $DIR/parse-error.rs:133:30 + --> $DIR/parse-error.rs:130:30 | LL | global_asm!("{}", options(), clobber_abi("C"), const FOO); | ^^^^^^^^^^^^^^^^ error: `clobber_abi` cannot be used with `global_asm!` - --> $DIR/parse-error.rs:135:17 + --> $DIR/parse-error.rs:132:17 | LL | global_asm!("", clobber_abi("C"), clobber_abi("C")); | ^^^^^^^^^^^^^^^^ ^^^^^^^^^^^^^^^^ error: duplicate argument named `a` - --> $DIR/parse-error.rs:137:35 + --> $DIR/parse-error.rs:134:35 | LL | global_asm!("{a}", a = const FOO, a = const BAR); | ------------- ^^^^^^^^^^^^^ duplicate argument @@ -335,7 +335,7 @@ LL | global_asm!("{a}", a = const FOO, a = const BAR); | previously here error: argument never used - --> $DIR/parse-error.rs:137:35 + --> $DIR/parse-error.rs:134:35 | LL | global_asm!("{a}", a = const FOO, a = const BAR); | ^^^^^^^^^^^^^ argument never used @@ -343,67 +343,67 @@ LL | global_asm!("{a}", a = const FOO, a = const BAR); = help: if this argument is intentionally unused, consider using it in an asm comment: `"/* {1} */"` error: expected one of `#`, `clobber_abi`, `const`, `options`, or `sym`, found `""` - --> $DIR/parse-error.rs:140:28 + --> $DIR/parse-error.rs:137:28 | LL | global_asm!("", options(), ""); | ^^ expected one of `#`, `clobber_abi`, `const`, `options`, or `sym` error: expected one of `#`, `clobber_abi`, `const`, `options`, or `sym`, found `"{}"` - --> $DIR/parse-error.rs:142:30 + --> $DIR/parse-error.rs:139:30 | LL | global_asm!("{}", const FOO, "{}", const FOO); | ^^^^ expected one of `#`, `clobber_abi`, `const`, `options`, or `sym` error: asm template must be a string literal - --> $DIR/parse-error.rs:144:13 + --> $DIR/parse-error.rs:141:13 | LL | global_asm!(format!("{{{}}}", 0), const FOO); | ^^^^^^^^^^^^^^^^^^^^ error: asm template must be a string literal - --> $DIR/parse-error.rs:146:20 + --> $DIR/parse-error.rs:143:20 | LL | global_asm!("{1}", format!("{{{}}}", 0), const FOO, const BAR); | ^^^^^^^^^^^^^^^^^^^^ error: the `in` operand cannot be used with `global_asm!` - --> $DIR/parse-error.rs:149:19 + --> $DIR/parse-error.rs:146:19 | LL | global_asm!("{}", in(reg)); | ^^ the `in` operand is not meaningful for global-scoped inline assembly, remove it error: the `out` operand cannot be used with `global_asm!` - --> $DIR/parse-error.rs:151:19 + --> $DIR/parse-error.rs:148:19 | LL | global_asm!("{}", out(reg)); | ^^^ the `out` operand is not meaningful for global-scoped inline assembly, remove it error: the `lateout` operand cannot be used with `global_asm!` - --> $DIR/parse-error.rs:153:19 + --> $DIR/parse-error.rs:150:19 | LL | global_asm!("{}", lateout(reg)); | ^^^^^^^ the `lateout` operand is not meaningful for global-scoped inline assembly, remove it error: the `inout` operand cannot be used with `global_asm!` - --> $DIR/parse-error.rs:155:19 + --> $DIR/parse-error.rs:152:19 | LL | global_asm!("{}", inout(reg)); | ^^^^^ the `inout` operand is not meaningful for global-scoped inline assembly, remove it error: the `inlateout` operand cannot be used with `global_asm!` - --> $DIR/parse-error.rs:157:19 + --> $DIR/parse-error.rs:154:19 | LL | global_asm!("{}", inlateout(reg)); | ^^^^^^^^^ the `inlateout` operand is not meaningful for global-scoped inline assembly, remove it error: the `label` operand cannot be used with `global_asm!` - --> $DIR/parse-error.rs:159:19 + --> $DIR/parse-error.rs:156:19 | LL | global_asm!("{}", label(reg)); | ^^^^^ the `label` operand is not meaningful for global-scoped inline assembly, remove it error[E0435]: attempt to use a non-constant value in a constant - --> $DIR/parse-error.rs:40:37 + --> $DIR/parse-error.rs:37:37 | LL | asm!("{}", options(), const foo); | ^^^ non-constant value @@ -415,7 +415,7 @@ LL + const foo: /* Type */ = 0; | error[E0435]: attempt to use a non-constant value in a constant - --> $DIR/parse-error.rs:72:44 + --> $DIR/parse-error.rs:69:44 | LL | asm!("{}", clobber_abi("C"), const foo); | ^^^ non-constant value @@ -427,7 +427,7 @@ LL + const foo: /* Type */ = 0; | error[E0435]: attempt to use a non-constant value in a constant - --> $DIR/parse-error.rs:75:55 + --> $DIR/parse-error.rs:72:55 | LL | asm!("{}", options(), clobber_abi("C"), const foo); | ^^^ non-constant value @@ -439,7 +439,7 @@ LL + const foo: /* Type */ = 0; | error[E0435]: attempt to use a non-constant value in a constant - --> $DIR/parse-error.rs:77:31 + --> $DIR/parse-error.rs:74:31 | LL | asm!("{a}", a = const foo, a = const bar); | ^^^ non-constant value @@ -451,7 +451,7 @@ LL + const foo: /* Type */ = 0; | error[E0435]: attempt to use a non-constant value in a constant - --> $DIR/parse-error.rs:77:46 + --> $DIR/parse-error.rs:74:46 | LL | asm!("{a}", a = const foo, a = const bar); | ^^^ non-constant value diff --git a/tests/ui/asm/powerpc/bad-reg.rs b/tests/ui/asm/powerpc/bad-reg.rs index 4e45a5b61a8df..c0615a8161919 100644 --- a/tests/ui/asm/powerpc/bad-reg.rs +++ b/tests/ui/asm/powerpc/bad-reg.rs @@ -381,3 +381,8 @@ fn f() { //~^ ERROR can only be used as a clobber } } + +//@ reference: asm.register-names.not-for-io +//@ reference: asm.register-operands.error-overlapping +//@ reference: asm.register-operands.supported-register-classes +//@ reference: asm.register-operands.value-type-constraints diff --git a/tests/ui/asm/reg-conflict.rs b/tests/ui/asm/reg-conflict.rs index 606735051f7a3..aea7817cd70a7 100644 --- a/tests/ui/asm/reg-conflict.rs +++ b/tests/ui/asm/reg-conflict.rs @@ -16,3 +16,5 @@ fn main() { //~^ ERROR register `s1` conflicts with register `d0` } } + +//@ reference: asm.register-operands.error-overlapping diff --git a/tests/ui/asm/riscv/bad-reg.rs b/tests/ui/asm/riscv/bad-reg.rs index 1a3784f084a08..d3f77d210b08b 100644 --- a/tests/ui/asm/riscv/bad-reg.rs +++ b/tests/ui/asm/riscv/bad-reg.rs @@ -100,3 +100,8 @@ fn f() { //~^ ERROR can only be used as a clobber } } + +//@ reference: asm.register-names.not-for-io +//@ reference: asm.register-names.supported-register-aliases +//@ reference: asm.register-operands.supported-register-classes +//@ reference: asm.register-operands.value-type-constraints diff --git a/tests/ui/asm/s390x/bad-reg.rs b/tests/ui/asm/s390x/bad-reg.rs index a6b2b869a851e..1a77c240568b7 100644 --- a/tests/ui/asm/s390x/bad-reg.rs +++ b/tests/ui/asm/s390x/bad-reg.rs @@ -142,3 +142,8 @@ fn f() { //~^ ERROR invalid register `f16`: unknown register } } + +//@ reference: asm.register-names.not-for-io +//@ reference: asm.register-operands.error-overlapping +//@ reference: asm.register-operands.supported-register-classes +//@ reference: asm.register-operands.value-type-constraints diff --git a/tests/ui/asm/type-check-1.rs b/tests/ui/asm/type-check-1.rs index 4dc30fb58385c..239c9636f24af 100644 --- a/tests/ui/asm/type-check-1.rs +++ b/tests/ui/asm/type-check-1.rs @@ -28,3 +28,7 @@ fn main() { //~| ERROR cannot use value of type `[u64]` for inline assembly } } + +//@ reference: asm.operand-type.supported-operands-inout +//@ reference: asm.operand-type.supported-operands-out +//@ reference: asm.register-operands.allowed-types diff --git a/tests/ui/asm/x86_64/bad-clobber-abi.rs b/tests/ui/asm/x86_64/bad-clobber-abi.rs index 1b27c427b4df8..4f821f5581055 100644 --- a/tests/ui/asm/x86_64/bad-clobber-abi.rs +++ b/tests/ui/asm/x86_64/bad-clobber-abi.rs @@ -35,3 +35,6 @@ fn main() { //~^ ERROR `win64` ABI specified multiple times } } + +//@ reference: asm.abi-clobbers.many +//@ reference: asm.abi-clobbers.supported-abis diff --git a/tests/ui/asm/x86_64/bad-options.rs b/tests/ui/asm/x86_64/bad-options.rs index 594ee6016541a..e1a916cfbf6e8 100644 --- a/tests/ui/asm/x86_64/bad-options.rs +++ b/tests/ui/asm/x86_64/bad-options.rs @@ -49,3 +49,10 @@ global_asm!("", options(nostack)); //~^ ERROR the `nostack` option cannot be used with `global_asm!` global_asm!("", options(preserves_flags)); //~^ ERROR the `preserves_flags` option cannot be used with `global_asm!` + +//@ reference: asm.abi-clobbers.must-specify +//@ reference: asm.abi-clobbers.supported-abis +//@ reference: asm.options.checks-mutually-exclusive +//@ reference: asm.options.checks-noreturn +//@ reference: asm.options.checks-pure +//@ reference: asm.options.global_asm-restriction diff --git a/tests/ui/asm/x86_64/bad-reg.rs b/tests/ui/asm/x86_64/bad-reg.rs index 3e9858f4d9664..a96ce7ba7015f 100644 --- a/tests/ui/asm/x86_64/bad-reg.rs +++ b/tests/ui/asm/x86_64/bad-reg.rs @@ -91,3 +91,13 @@ fn main() { asm!("/* {:z} */", out(zmm_reg) xmmword); } } + +//@ reference: asm.operand-type.supported-operands-lateout +//@ reference: asm.register-names.not-for-io +//@ reference: asm.register-operands.equivalence-to-base-register +//@ reference: asm.register-operands.error-overlapping +//@ reference: asm.register-operands.error-two-operands +//@ reference: asm.register-operands.register-or-class +//@ reference: asm.register-operands.supported-register-classes +//@ reference: asm.register-operands.value-type-constraints +//@ reference: asm.template-modifiers.supported-modifiers diff --git a/tests/ui/asm/x86_64/const.rs b/tests/ui/asm/x86_64/const.rs index eaaaf92e823b4..6a8197403d333 100644 --- a/tests/ui/asm/x86_64/const.rs +++ b/tests/ui/asm/x86_64/const.rs @@ -38,3 +38,5 @@ fn main() { global_asm!("mov eax, {}", const 5); global_asm!("mov eax, {}", const constfn(5)); global_asm!("mov eax, {}", const constfn(5) + constfn(5)); + +//@ reference: asm.operand-type.supported-operands-const diff --git a/tests/ui/asm/x86_64/global_asm_escape.rs b/tests/ui/asm/x86_64/global_asm_escape.rs index 59214e958a85b..58935e14bda4b 100644 --- a/tests/ui/asm/x86_64/global_asm_escape.rs +++ b/tests/ui/asm/x86_64/global_asm_escape.rs @@ -15,3 +15,5 @@ core::arch::global_asm!(".global my_exit", "my_exit:", "jmp {}", sym exit); fn main() { my_exit(0); } + +//@ reference: asm.operand-type.supported-operands-sym diff --git a/tests/ui/asm/x86_64/goto-block-safe.rs b/tests/ui/asm/x86_64/goto-block-safe.rs index 1364425b07ac1..7aa8363b59991 100644 --- a/tests/ui/asm/x86_64/goto-block-safe.rs +++ b/tests/ui/asm/x86_64/goto-block-safe.rs @@ -26,3 +26,5 @@ fn goto_fallthough() { fn main() { goto_fallthough(); } + +//@ reference: asm.operand-type.supported-operands-label diff --git a/tests/ui/asm/x86_64/goto.rs b/tests/ui/asm/x86_64/goto.rs index 455bb3239895b..1b2a9312f36c2 100644 --- a/tests/ui/asm/x86_64/goto.rs +++ b/tests/ui/asm/x86_64/goto.rs @@ -157,3 +157,6 @@ fn main() { goto_noreturn(); goto_noreturn_diverge(); } + +//@ reference: asm.operand-type.supported-operands-label +//@ reference: asm.options.supported-options-noreturn diff --git a/tests/ui/asm/x86_64/issue-96797.rs b/tests/ui/asm/x86_64/issue-96797.rs index 5d3bbbb74bf56..3f1f71be021b6 100644 --- a/tests/ui/asm/x86_64/issue-96797.rs +++ b/tests/ui/asm/x86_64/issue-96797.rs @@ -31,3 +31,6 @@ fn main() { } unsafe { call_foobar() }; } + +//@ reference: asm.directives.supported-directives +//@ reference: asm.operand-type.supported-operands-sym diff --git a/tests/ui/asm/x86_64/multiple-clobber-abi.rs b/tests/ui/asm/x86_64/multiple-clobber-abi.rs index bf241b9771b43..b50b654121ad8 100644 --- a/tests/ui/asm/x86_64/multiple-clobber-abi.rs +++ b/tests/ui/asm/x86_64/multiple-clobber-abi.rs @@ -31,3 +31,7 @@ fn main() { } assert_eq!((x, y), (8, 12)); } + +//@ reference: asm.abi-clobbers.explicit-have-precedence +//@ reference: asm.abi-clobbers.intro +//@ reference: asm.abi-clobbers.many diff --git a/tests/ui/asm/x86_64/srcloc.rs b/tests/ui/asm/x86_64/srcloc.rs index 9bbd20340e3ab..cdb6acf9676d2 100644 --- a/tests/ui/asm/x86_64/srcloc.rs +++ b/tests/ui/asm/x86_64/srcloc.rs @@ -137,3 +137,6 @@ fn main() { //~^^ ERROR: invalid instruction mnemonic 'invalid_instruction' } } + +//@ reference: asm.ts-args.one-or-more +//@ reference: asm.validity.non-exhaustive diff --git a/tests/ui/asm/x86_64/sym.rs b/tests/ui/asm/x86_64/sym.rs index 0a86bd66ccbc1..e8611189983be 100644 --- a/tests/ui/asm/x86_64/sym.rs +++ b/tests/ui/asm/x86_64/sym.rs @@ -82,3 +82,5 @@ fn main() { .join() .unwrap(); } + +//@ reference: asm.operand-type.supported-operands-sym diff --git a/tests/ui/asm/x86_64/target-feature-attr.rs b/tests/ui/asm/x86_64/target-feature-attr.rs index ada5fecd797e3..69d4db67b7721 100644 --- a/tests/ui/asm/x86_64/target-feature-attr.rs +++ b/tests/ui/asm/x86_64/target-feature-attr.rs @@ -45,3 +45,5 @@ fn main() { bar(); } } + +//@ reference: asm.register-operands.value-type-constraints diff --git a/tests/ui/asm/x86_64/type-check-2.rs b/tests/ui/asm/x86_64/type-check-2.rs index ed5ad6fbc4591..857f011ef8d2a 100644 --- a/tests/ui/asm/x86_64/type-check-2.rs +++ b/tests/ui/asm/x86_64/type-check-2.rs @@ -74,3 +74,8 @@ fn test2() { } fn main() {} + +//@ reference: asm.operand-type.supported-operands-in +//@ reference: asm.operand-type.supported-operands-inout +//@ reference: asm.operand-type.supported-operands-out +//@ reference: asm.register-operands.allowed-types diff --git a/tests/ui/asm/x86_64/type-check-3.rs b/tests/ui/asm/x86_64/type-check-3.rs index bfb795d262455..71afb8c97638a 100644 --- a/tests/ui/asm/x86_64/type-check-3.rs +++ b/tests/ui/asm/x86_64/type-check-3.rs @@ -69,3 +69,9 @@ fn main() { asm!("{:r}", inout(reg) main => val_u64); } } + +//@ reference: asm.operand-type.supported-operands-inout-arrow +//@ reference: asm.register-operands.separate-input-output +//@ reference: asm.register-operands.value-type-constraints +//@ reference: asm.template-modifiers.smaller-value +//@ reference: asm.template-modifiers.supported-modifiers diff --git a/tests/ui/asm/x86_64/type-check-5.rs b/tests/ui/asm/x86_64/type-check-5.rs index f181fe44a3f12..aa7d3b2d2308b 100644 --- a/tests/ui/asm/x86_64/type-check-5.rs +++ b/tests/ui/asm/x86_64/type-check-5.rs @@ -55,3 +55,9 @@ fn main() { asm!("{}", in(reg) u); } } + +//@ reference: asm.operand-type.supported-operands-in +//@ reference: asm.operand-type.supported-operands-inout +//@ reference: asm.operand-type.supported-operands-out +//@ reference: asm.operand-type.supported-operands-sym +//@ reference: asm.register-operands.allowed-types diff --git a/tests/ui/asm/x86_64/x86_64_parse_error.rs b/tests/ui/asm/x86_64/x86_64_parse_error.rs index 3d011416c6f57..582d8c76ed508 100644 --- a/tests/ui/asm/x86_64/x86_64_parse_error.rs +++ b/tests/ui/asm/x86_64/x86_64_parse_error.rs @@ -23,3 +23,5 @@ fn main() { //~| ERROR attempt to use a non-constant value in a constant } } + +//@ reference: asm.ts-args.positional-first diff --git a/tests/ui/async-await/in-trait/dont-project-to-specializable-projection.stderr b/tests/ui/async-await/in-trait/dont-project-to-specializable-projection.stderr index fb80fe2b5a0d8..9a07c077518a5 100644 --- a/tests/ui/async-await/in-trait/dont-project-to-specializable-projection.stderr +++ b/tests/ui/async-await/in-trait/dont-project-to-specializable-projection.stderr @@ -26,13 +26,23 @@ error[E0599]: no method named `poll` found for struct `Pin<&mut impl Future $DIR/dont-project-to-specializable-projection.rs:48:28 | LL | match fut.as_mut().poll(ctx) { - | ^^^^ method not found in `Pin<&mut impl Future>` + | ------ ^^^^ method not found in `Pin<&mut impl Future>` + | | + | this method is `std::pin::Pin::::as_mut` | --> $SRC_DIR/core/src/future/future.rs:LL:COL | = note: the method is available for `Pin<&mut impl Future>` here - | +note: this returns `Pin<&mut impl Future>` + --> $SRC_DIR/core/src/pin.rs:LL:COL +note: you might have meant to call `std::convert::AsMut::as_mut` instead + --> $SRC_DIR/core/src/convert/mod.rs:LL:COL = help: items from traits can only be used if the trait is in scope +help: consider calling `std::convert::AsMut::as_mut` using the fully-qualified path + | +LL - match fut.as_mut().poll(ctx) { +LL + match <_ as AsMut<_>>::as_mut(&mut fut).poll(ctx) { + | help: trait `Future` which provides `poll` is implemented but not in scope; perhaps you want to import it | LL + use std::future::Future; diff --git a/tests/ui/borrowck/const-cannot-move-shared-ref.rs b/tests/ui/borrowck/const-cannot-move-shared-ref.rs new file mode 100644 index 0000000000000..96a38a0e9f00e --- /dev/null +++ b/tests/ui/borrowck/const-cannot-move-shared-ref.rs @@ -0,0 +1,10 @@ +// Checks whether borrow checking visits constants correctly + +struct NonCopy(u8); + +const C: () = { + let &moved = &NonCopy(0); + //~^ ERROR cannot move out of a shared reference +}; + +fn main() { } diff --git a/tests/ui/borrowck/const-cannot-move-shared-ref.stderr b/tests/ui/borrowck/const-cannot-move-shared-ref.stderr new file mode 100644 index 0000000000000..2daac49319ab3 --- /dev/null +++ b/tests/ui/borrowck/const-cannot-move-shared-ref.stderr @@ -0,0 +1,17 @@ +error[E0507]: cannot move out of a shared reference + --> $DIR/const-cannot-move-shared-ref.rs:6:18 + | +LL | let &moved = &NonCopy(0); + | ----- ^^^^^^^^^^^ + | | + | data moved here because `moved` has type `NonCopy`, which does not implement the `Copy` trait + | +help: consider removing the borrow + | +LL - let &moved = &NonCopy(0); +LL + let moved = &NonCopy(0); + | + +error: aborting due to 1 previous error + +For more information about this error, try `rustc --explain E0507`. diff --git a/tests/ui/c-variadic/obligation-span.rs b/tests/ui/c-variadic/obligation-span.rs new file mode 100644 index 0000000000000..b14d645444fbd --- /dev/null +++ b/tests/ui/c-variadic/obligation-span.rs @@ -0,0 +1,15 @@ +// This test checks that the span of c-variadics is handled correctly when creating obligations + +struct NeedsCopy(T); + +extern "C" { + fn f1(...) -> NeedsCopy; + //~^ ERROR the trait bound `String: Copy` is not satisfied + fn f2(x: i32, ...) -> NeedsCopy; + //~^ ERROR the trait bound `String: Copy` is not satisfied + fn f3(..., x: i32) -> NeedsCopy; + //~^ ERROR `...` must be the last argument of a C-variadic function + //~| ERROR the trait bound `String: Copy` is not satisfied +} + +fn main() { } diff --git a/tests/ui/c-variadic/obligation-span.stderr b/tests/ui/c-variadic/obligation-span.stderr new file mode 100644 index 0000000000000..aaa329d70e3ee --- /dev/null +++ b/tests/ui/c-variadic/obligation-span.stderr @@ -0,0 +1,45 @@ +error: `...` must be the last argument of a C-variadic function + --> $DIR/obligation-span.rs:10:11 + | +LL | fn f3(..., x: i32) -> NeedsCopy; + | ^^^ + +error[E0277]: the trait bound `String: Copy` is not satisfied + --> $DIR/obligation-span.rs:6:19 + | +LL | fn f1(...) -> NeedsCopy; + | ^^^^^^^^^^^^^^^^^ the trait `Copy` is not implemented for `String` + | +note: required by a bound in `NeedsCopy` + --> $DIR/obligation-span.rs:3:21 + | +LL | struct NeedsCopy(T); + | ^^^^ required by this bound in `NeedsCopy` + +error[E0277]: the trait bound `String: Copy` is not satisfied + --> $DIR/obligation-span.rs:8:27 + | +LL | fn f2(x: i32, ...) -> NeedsCopy; + | ^^^^^^^^^^^^^^^^^ the trait `Copy` is not implemented for `String` + | +note: required by a bound in `NeedsCopy` + --> $DIR/obligation-span.rs:3:21 + | +LL | struct NeedsCopy(T); + | ^^^^ required by this bound in `NeedsCopy` + +error[E0277]: the trait bound `String: Copy` is not satisfied + --> $DIR/obligation-span.rs:10:27 + | +LL | fn f3(..., x: i32) -> NeedsCopy; + | ^^^^^^^^^^^^^^^^^ the trait `Copy` is not implemented for `String` + | +note: required by a bound in `NeedsCopy` + --> $DIR/obligation-span.rs:3:21 + | +LL | struct NeedsCopy(T); + | ^^^^ required by this bound in `NeedsCopy` + +error: aborting due to 4 previous errors + +For more information about this error, try `rustc --explain E0277`. diff --git a/tests/ui/coroutine/pack-coroutine-layout-flag.captures_only.stderr b/tests/ui/coroutine/pack-coroutine-layout-flag.captures_only.stderr new file mode 100644 index 0000000000000..70082dbbdba84 --- /dev/null +++ b/tests/ui/coroutine/pack-coroutine-layout-flag.captures_only.stderr @@ -0,0 +1,4 @@ +warning: `-Z pack-coroutine-layout=captures-only` is not yet implemented and will be ignored + +warning: 1 warning emitted + diff --git a/tests/ui/coroutine/pack-coroutine-layout-flag.invalid.stderr b/tests/ui/coroutine/pack-coroutine-layout-flag.invalid.stderr new file mode 100644 index 0000000000000..7694a756ef47f --- /dev/null +++ b/tests/ui/coroutine/pack-coroutine-layout-flag.invalid.stderr @@ -0,0 +1,2 @@ +error: incorrect value `invalid` for unstable option `pack-coroutine-layout` - either `classic` or `captures-only` was expected + diff --git a/tests/ui/coroutine/pack-coroutine-layout-flag.rs b/tests/ui/coroutine/pack-coroutine-layout-flag.rs new file mode 100644 index 0000000000000..735e3e6807cfd --- /dev/null +++ b/tests/ui/coroutine/pack-coroutine-layout-flag.rs @@ -0,0 +1,15 @@ +//@ edition: 2021 +//@ revisions: classic captures_only invalid +//@ [classic] check-pass +//@ [classic] compile-flags: -Z pack-coroutine-layout=classic +//@ [captures_only] check-pass +//@ [captures_only] compile-flags: -Z pack-coroutine-layout=captures-only +//@ [invalid] compile-flags: -Z pack-coroutine-layout=invalid +//[captures_only]~? WARN `-Z pack-coroutine-layout=captures-only` is not yet implemented and will be ignored +//[invalid]~? ERROR incorrect value `invalid` for unstable option `pack-coroutine-layout` - either `classic` or `captures-only` was expected + +#![crate_type = "lib"] + +pub async fn example(x: String) { + drop(x); +} diff --git a/tests/ui/feature-gates/feature-gate-asm_experimental_arch.rs b/tests/ui/feature-gates/feature-gate-asm_experimental_arch.rs index 450a4f40beb0d..864c3315456ca 100644 --- a/tests/ui/feature-gates/feature-gate-asm_experimental_arch.rs +++ b/tests/ui/feature-gates/feature-gate-asm_experimental_arch.rs @@ -14,3 +14,5 @@ unsafe fn main() { asm!(""); //~^ ERROR inline assembly is not stable yet on this architecture } + +//@ reference: asm.stable-targets diff --git a/tests/ui/feature-gates/feature-gate-asm_goto_with_outputs.rs b/tests/ui/feature-gates/feature-gate-asm_goto_with_outputs.rs index 26b7d5d2fbfbb..884c2ef41b031 100644 --- a/tests/ui/feature-gates/feature-gate-asm_goto_with_outputs.rs +++ b/tests/ui/feature-gates/feature-gate-asm_goto_with_outputs.rs @@ -9,3 +9,5 @@ fn main() { //~^ ERROR using both label and output operands for inline assembly is unstable } } + +//@ reference: asm.options.checks-label-with-outputs diff --git a/tests/ui/feature-gates/feature-gate-type_info.rs b/tests/ui/feature-gates/feature-gate-type_info.rs index 001a797b16a16..9bb6d8aee587d 100644 --- a/tests/ui/feature-gates/feature-gate-type_info.rs +++ b/tests/ui/feature-gates/feature-gate-type_info.rs @@ -1,4 +1,7 @@ -#[reflection_placeholder::a] //~ ERROR cannot find module or crate `reflection_placeholder` in this scope [E0433] -struct A; +#![feature(register_tool)] +#![register_tool(aaa(asdf))] +//~^ ERROR: tool attribute options are currently unstable +#![register_tool(bbb(reflect))] +//~^ ERROR: tool attribute options are currently unstable fn main() {} diff --git a/tests/ui/feature-gates/feature-gate-type_info.stderr b/tests/ui/feature-gates/feature-gate-type_info.stderr index ffbec352f775b..05006ab0ce6e6 100644 --- a/tests/ui/feature-gates/feature-gate-type_info.stderr +++ b/tests/ui/feature-gates/feature-gate-type_info.stderr @@ -1,9 +1,23 @@ -error[E0433]: cannot find module or crate `reflection_placeholder` in this scope - --> $DIR/feature-gate-type_info.rs:1:3 +error[E0658]: tool attribute options are currently unstable + --> $DIR/feature-gate-type_info.rs:2:18 | -LL | #[reflection_placeholder::a] - | ^^^^^^^^^^^^^^^^^^^^^^ use of unresolved module or unlinked crate `reflection_placeholder` +LL | #![register_tool(aaa(asdf))] + | ^^^^^^^^^ + | + = note: see issue #146922 for more information + = help: add `#![feature(type_info)]` to the crate attributes to enable + = note: this compiler was built on YYYY-MM-DD; consider upgrading it if it is out of date + +error[E0658]: tool attribute options are currently unstable + --> $DIR/feature-gate-type_info.rs:4:18 + | +LL | #![register_tool(bbb(reflect))] + | ^^^^^^^^^^^^ + | + = note: see issue #146922 for more information + = help: add `#![feature(type_info)]` to the crate attributes to enable + = note: this compiler was built on YYYY-MM-DD; consider upgrading it if it is out of date -error: aborting due to 1 previous error +error: aborting due to 2 previous errors -For more information about this error, try `rustc --explain E0433`. +For more information about this error, try `rustc --explain E0658`. diff --git a/tests/ui/impl-trait/no-method-suggested-traits.stderr b/tests/ui/impl-trait/no-method-suggested-traits.stderr index 1524679f8ba34..9115d814c404e 100644 --- a/tests/ui/impl-trait/no-method-suggested-traits.stderr +++ b/tests/ui/impl-trait/no-method-suggested-traits.stderr @@ -2,7 +2,7 @@ error[E0599]: no method named `method` found for type `u32` in the current scope --> $DIR/no-method-suggested-traits.rs:26:10 | LL | 1u32.method(); - | ^^^^^^ + | ^^^^^^ method not found in `u32` | = help: items from traits can only be used if the trait is in scope help: the following traits which provide `method` are implemented but not in scope; perhaps you want to import one of them @@ -11,16 +11,12 @@ LL + use crate::foo::Bar; | LL + use crate::no_method_suggested_traits::foo::PubPub; | -help: there is a method `method2` with a similar name - | -LL | 1u32.method2(); - | + error[E0599]: no method named `method` found for struct `Rc<&mut Box<&u32>>` in the current scope --> $DIR/no-method-suggested-traits.rs:29:44 | LL | std::rc::Rc::new(&mut Box::new(&1u32)).method(); - | ^^^^^^ + | ^^^^^^ method not found in `Rc<&mut Box<&u32>>` | = help: items from traits can only be used if the trait is in scope help: the following traits which provide `method` are implemented but not in scope; perhaps you want to import one of them @@ -29,10 +25,6 @@ LL + use crate::foo::Bar; | LL + use crate::no_method_suggested_traits::foo::PubPub; | -help: there is a method `method2` with a similar name - | -LL | std::rc::Rc::new(&mut Box::new(&1u32)).method2(); - | + error[E0599]: no method named `method` found for type `char` in the current scope --> $DIR/no-method-suggested-traits.rs:33:9 @@ -41,39 +33,31 @@ LL | fn method(&self) {} | ------ the method is available for `char` here ... LL | 'a'.method(); - | ^^^^^^ + | ^^^^^^ method not found in `char` | = help: items from traits can only be used if the trait is in scope help: trait `Bar` which provides `method` is implemented but not in scope; perhaps you want to import it | LL + use crate::foo::Bar; | -help: there is a method `method2` with a similar name - | -LL | 'a'.method2(); - | + error[E0599]: no method named `method` found for struct `Rc<&mut Box<&char>>` in the current scope --> $DIR/no-method-suggested-traits.rs:35:43 | LL | std::rc::Rc::new(&mut Box::new(&'a')).method(); - | ^^^^^^ + | ^^^^^^ method not found in `Rc<&mut Box<&char>>` | = help: items from traits can only be used if the trait is in scope help: trait `Bar` which provides `method` is implemented but not in scope; perhaps you want to import it | LL + use crate::foo::Bar; | -help: there is a method `method2` with a similar name - | -LL | std::rc::Rc::new(&mut Box::new(&'a')).method2(); - | + error[E0599]: no method named `method` found for type `i32` in the current scope --> $DIR/no-method-suggested-traits.rs:38:10 | LL | 1i32.method(); - | ^^^^^^ + | ^^^^^^ method not found in `i32` | ::: $DIR/auxiliary/no_method_suggested_traits.rs:8:12 | @@ -85,26 +69,18 @@ help: trait `PubPub` which provides `method` is implemented but not in scope; pe | LL + use crate::no_method_suggested_traits::foo::PubPub; | -help: there is a method `method3` with a similar name - | -LL | 1i32.method3(); - | + error[E0599]: no method named `method` found for struct `Rc<&mut Box<&i32>>` in the current scope --> $DIR/no-method-suggested-traits.rs:40:44 | LL | std::rc::Rc::new(&mut Box::new(&1i32)).method(); - | ^^^^^^ + | ^^^^^^ method not found in `Rc<&mut Box<&i32>>` | = help: items from traits can only be used if the trait is in scope help: trait `PubPub` which provides `method` is implemented but not in scope; perhaps you want to import it | LL + use crate::no_method_suggested_traits::foo::PubPub; | -help: there is a method `method3` with a similar name - | -LL | std::rc::Rc::new(&mut Box::new(&1i32)).method3(); - | + error[E0599]: no method named `method` found for struct `Foo` in the current scope --> $DIR/no-method-suggested-traits.rs:43:9 diff --git a/tests/ui/macros/missing-writer-issue-139830.stderr b/tests/ui/macros/missing-writer-issue-139830.stderr index 0a1c6f6f3eac9..3f5172eacab94 100644 --- a/tests/ui/macros/missing-writer-issue-139830.stderr +++ b/tests/ui/macros/missing-writer-issue-139830.stderr @@ -2,7 +2,7 @@ error[E0599]: cannot write into `String` --> $DIR/missing-writer-issue-139830.rs:7:20 | LL | let _ = write!(buf, "foo"); - | ^^^ + | -------^^^-------- method not found in `String` | --> $SRC_DIR/core/src/fmt/mod.rs:LL:COL | diff --git a/tests/ui/methods/method-shadowed-by-trait-in-binop.rs b/tests/ui/methods/method-shadowed-by-trait-in-binop.rs new file mode 100644 index 0000000000000..a3ef0fb6178e8 --- /dev/null +++ b/tests/ui/methods/method-shadowed-by-trait-in-binop.rs @@ -0,0 +1,31 @@ +// Regression test for #66630. +use std::sync::Mutex; +use std::cell::RefCell; +use std::borrow::Borrow; + +struct A { + child: Mutex>, +} + +impl A { + fn is_good(&self) -> bool { + let cell = self.child.lock().unwrap(); + let opt_target = cell.borrow(); + //~^ NOTE: this method is `std::borrow::Borrow::borrow` + //~| NOTE: this method is `std::borrow::Borrow::borrow` + let _ = opt_target.abs(); //~ ERROR: no method named `abs` found for + //~^ NOTE: method not found in `&std::sync::MutexGuard<'_, RefCell>` + //~| NOTE: this returns `&std::sync::MutexGuard<'_, RefCell>` + //~| NOTE: you might have meant to call `std::cell::RefCell::::borrow` instead + let _ = *opt_target > 1; //~ ERROR: binary operation `>` cannot be applied + //~^ NOTE: std::sync::MutexGuard<'_, RefCell> + //~| NOTE: `std::sync::MutexGuard<'_, RefCell>` does not implement `PartialOrd<{integer}>` + //~| NOTE: this returns `std::sync::MutexGuard<'_, RefCell>` + //~| NOTE: you might have meant to call `std::cell::RefCell::::borrow` instead + //~| NOTE: {integer} + 1 < *opt_target //~ ERROR: E0277 + //~^ NOTE: no implementation for `{integer} < std::sync::MutexGuard<'_, RefCell>` + } +} + +fn main() {} diff --git a/tests/ui/methods/method-shadowed-by-trait-in-binop.stderr b/tests/ui/methods/method-shadowed-by-trait-in-binop.stderr new file mode 100644 index 0000000000000..7faa37c6f16d5 --- /dev/null +++ b/tests/ui/methods/method-shadowed-by-trait-in-binop.stderr @@ -0,0 +1,67 @@ +error[E0599]: no method named `abs` found for reference `&std::sync::MutexGuard<'_, RefCell>` in the current scope + --> $DIR/method-shadowed-by-trait-in-binop.rs:16:28 + | +LL | let opt_target = cell.borrow(); + | ------ this method is `std::borrow::Borrow::borrow` +... +LL | let _ = opt_target.abs(); + | ^^^ method not found in `&std::sync::MutexGuard<'_, RefCell>` + | +note: this returns `&std::sync::MutexGuard<'_, RefCell>` + --> $SRC_DIR/core/src/borrow.rs:LL:COL +note: you might have meant to call `std::cell::RefCell::::borrow` instead + --> $SRC_DIR/core/src/cell.rs:LL:COL +help: consider calling `std::cell::RefCell::::borrow` using the fully-qualified path + | +LL - let opt_target = cell.borrow(); +LL + let opt_target = RefCell::::borrow(&cell); + | + +error[E0369]: binary operation `>` cannot be applied to type `std::sync::MutexGuard<'_, RefCell>` + --> $DIR/method-shadowed-by-trait-in-binop.rs:20:29 + | +LL | let opt_target = cell.borrow(); + | ------ this method is `std::borrow::Borrow::borrow` +... +LL | let _ = *opt_target > 1; + | ----------- ^ - {integer} + | | + | std::sync::MutexGuard<'_, RefCell> + | +note: `std::sync::MutexGuard<'_, RefCell>` does not implement `PartialOrd<{integer}>` + --> $SRC_DIR/std/src/sync/poison/mutex.rs:LL:COL + ::: $SRC_DIR/std/src/sync/poison/mutex.rs:LL:COL + | + = note: `std::sync::MutexGuard<'_, RefCell>` is defined in another crate +note: this returns `std::sync::MutexGuard<'_, RefCell>` + --> $SRC_DIR/core/src/borrow.rs:LL:COL +note: you might have meant to call `std::cell::RefCell::::borrow` instead + --> $SRC_DIR/core/src/cell.rs:LL:COL +help: consider calling `std::cell::RefCell::::borrow` using the fully-qualified path + | +LL - let opt_target = cell.borrow(); +LL + let opt_target = RefCell::::borrow(&cell); + | + +error[E0277]: can't compare `{integer}` with `std::sync::MutexGuard<'_, RefCell>` + --> $DIR/method-shadowed-by-trait-in-binop.rs:26:11 + | +LL | 1 < *opt_target + | ^ no implementation for `{integer} < std::sync::MutexGuard<'_, RefCell>` and `{integer} > std::sync::MutexGuard<'_, RefCell>` + | + = help: the trait `PartialOrd>>` is not implemented for `{integer}` + = help: the following other types implement trait `PartialOrd`: + f128 + f16 + f32 + f64 + i128 + i16 + i32 + i64 + and 8 others + +error: aborting due to 3 previous errors + +Some errors have detailed explanations: E0277, E0369, E0599. +For more information about an error, try `rustc --explain E0277`. diff --git a/tests/ui/methods/method-shadowed-by-trait.rs b/tests/ui/methods/method-shadowed-by-trait.rs new file mode 100644 index 0000000000000..b44158318bdbe --- /dev/null +++ b/tests/ui/methods/method-shadowed-by-trait.rs @@ -0,0 +1,122 @@ +// Show the diagnostic for cases where a method is expected by the user but a different one is +// shaddowing it causing a field access to fail. Test for #93726. + +use std::cell::RefCell; +use std::rc::Rc; +use std::borrow::BorrowMut; + +type NodeAlias = Option>>; + +#[derive(Clone, Debug, PartialEq)] +struct Node { + value: String, + next: NodeAlias, +} + +#[derive(Clone, Debug, PartialEq)] +struct TransactionLog { + head: NodeAlias, + tail: NodeAlias, + length: i32, +} + +impl Node { + fn new(value: String) -> Rc> { + Rc::new(RefCell::new(Node { value, next: None })) + } +} + +impl TransactionLog { + pub fn empty_list() -> TransactionLog { + TransactionLog { + head: None, + tail: None, + length: 0, + } + } + + pub fn append(&mut self, value: String) { + let node = Node::new(value); + match self.tail.take() { + Some(old_tail) => old_tail.borrow_mut().next = Some(node.clone()), + //~^ ERROR: no field `next` on type `&mut Rc>` + //~| NOTE: unknown field + //~| NOTE: this method is `std::borrow::BorrowMut::borrow_mut` + //~| NOTE: you might have meant to call `std::cell::RefCell::::borrow_mut` instead + //~| NOTE: this returns `&mut Rc>` + None => self.head = Some(node.clone()), + } + self.length += 1; + self.tail = Some(node); + } +} + + +struct S; +struct Other { + field: (), +} +impl Other { + fn method(&self) {} +} + +impl S { + fn foo(&self) -> Other { Other { field: () } } + //~^ NOTE: you might have meant to call + //~| NOTE: you might have meant to call + //~| NOTE: you might have meant to call + //~| NOTE: you might have meant to call +} +mod a { + use crate::{S, Other}; + pub trait T { + fn foo(&self) {} + //~^ NOTE: this returns `()` + //~| NOTE: this returns `()` + //~| NOTE: this returns `()` + //~| NOTE: this returns `()` + } + impl T for S {} + impl T for Box {} + pub trait K

{ + fn foo(&self) -> Other { Other { field : () } } + //~^ NOTE: you might have meant to call + //~| NOTE: you might have meant to call + //~| NOTE: you might have meant to call + //~| NOTE: you might have meant to call + } + impl K<()> for S {} + impl K for Box {} + pub trait V { + fn foo(&self) -> Other; + //~^ NOTE: you might have meant to call + //~| NOTE: you might have meant to call + //~| NOTE: you might have meant to call + //~| NOTE: you might have meant to call + } + impl V for Box { + fn foo(&self) -> Other { Other { field : () } } + } + pub trait U { + fn foo(&self) {} // not suggested because its return type doesn't have the field + } + impl U for Box {} +} +use a::T; + +fn main() { + let x = Box::new(S); + x.foo().field; //~ ERROR: no field `field` on type `()` + //~^ NOTE: unknown field + //~| NOTE: this method is `a::T::foo` + let y = x.foo(); + //~^ NOTE: this method is `a::T::foo` + //~| NOTE: this method is `a::T::foo` + let _ = y.field; //~ ERROR: no field `field` on type `()` + //~^ NOTE: unknown field + x.foo().method(); //~ ERROR: no method named `method` found for unit type `()` in the current scope + //~^ NOTE: method not found in `()` + //~| NOTE: this method is `a::T::foo` + let _ = y.method(); //~ ERROR: no method named `method` found for unit type `()` in the current scope + //~^ NOTE: method not found in `()` +} diff --git a/tests/ui/methods/method-shadowed-by-trait.stderr b/tests/ui/methods/method-shadowed-by-trait.stderr new file mode 100644 index 0000000000000..9f86447ce5759 --- /dev/null +++ b/tests/ui/methods/method-shadowed-by-trait.stderr @@ -0,0 +1,216 @@ +error[E0609]: no field `next` on type `&mut Rc>` + --> $DIR/method-shadowed-by-trait.rs:41:53 + | +LL | Some(old_tail) => old_tail.borrow_mut().next = Some(node.clone()), + | ---------- ^^^^ unknown field + | | + | this method is `std::borrow::BorrowMut::borrow_mut` + | +note: this returns `&mut Rc>` + --> $SRC_DIR/core/src/borrow.rs:LL:COL +note: you might have meant to call `std::cell::RefCell::::borrow_mut` instead + --> $SRC_DIR/core/src/cell.rs:LL:COL +help: consider calling `std::cell::RefCell::::borrow_mut` using the fully-qualified path + | +LL - Some(old_tail) => old_tail.borrow_mut().next = Some(node.clone()), +LL + Some(old_tail) => RefCell::::borrow_mut(&old_tail).next = Some(node.clone()), + | + +error[E0609]: no field `field` on type `()` + --> $DIR/method-shadowed-by-trait.rs:109:13 + | +LL | x.foo().field; + | --- ^^^^^ unknown field + | | + | this method is `a::T::foo` + | +note: this returns `()` + --> $DIR/method-shadowed-by-trait.rs:73:9 + | +LL | pub trait T { +LL | fn foo(&self) {} + | ^^^^^^^^^^^^^ +note: you might have meant to call `a::K::foo` instead + --> $DIR/method-shadowed-by-trait.rs:82:9 + | +LL | pub trait K

{ +LL | fn foo(&self) -> Other { Other { field : () } } + | ^^^^^^^^^^^^^^^^^^^^^^ +note: you might have meant to call `a::V::foo` instead + --> $DIR/method-shadowed-by-trait.rs:91:9 + | +LL | pub trait V { +LL | fn foo(&self) -> Other; + | ^^^^^^^^^^^^^^^^^^^^^^^ +note: you might have meant to call `S::foo` instead + --> $DIR/method-shadowed-by-trait.rs:64:5 + | +LL | impl S { +LL | fn foo(&self) -> Other { Other { field: () } } + | ^^^^^^^^^^^^^^^^^^^^^^ +help: consider calling `a::K::foo` using the fully-qualified path + | +LL - x.foo().field; +LL + <_ as K<_>>::foo(&x).field; + | +help: consider calling `a::V::foo` using the fully-qualified path + | +LL - x.foo().field; +LL + <_ as V>::foo(&x).field; + | +help: consider calling `S::foo` using the fully-qualified path + | +LL - x.foo().field; +LL + S::foo(&x).field; + | + +error[E0609]: no field `field` on type `()` + --> $DIR/method-shadowed-by-trait.rs:115:15 + | +LL | let y = x.foo(); + | --- this method is `a::T::foo` +... +LL | let _ = y.field; + | ^^^^^ unknown field + | +note: this returns `()` + --> $DIR/method-shadowed-by-trait.rs:73:9 + | +LL | pub trait T { +LL | fn foo(&self) {} + | ^^^^^^^^^^^^^ +note: you might have meant to call `a::K::foo` instead + --> $DIR/method-shadowed-by-trait.rs:82:9 + | +LL | pub trait K

{ +LL | fn foo(&self) -> Other { Other { field : () } } + | ^^^^^^^^^^^^^^^^^^^^^^ +note: you might have meant to call `a::V::foo` instead + --> $DIR/method-shadowed-by-trait.rs:91:9 + | +LL | pub trait V { +LL | fn foo(&self) -> Other; + | ^^^^^^^^^^^^^^^^^^^^^^^ +note: you might have meant to call `S::foo` instead + --> $DIR/method-shadowed-by-trait.rs:64:5 + | +LL | impl S { +LL | fn foo(&self) -> Other { Other { field: () } } + | ^^^^^^^^^^^^^^^^^^^^^^ +help: consider calling `a::K::foo` using the fully-qualified path + | +LL - let y = x.foo(); +LL + let y = <_ as K<_>>::foo(&x); + | +help: consider calling `a::V::foo` using the fully-qualified path + | +LL - let y = x.foo(); +LL + let y = <_ as V>::foo(&x); + | +help: consider calling `S::foo` using the fully-qualified path + | +LL - let y = x.foo(); +LL + let y = S::foo(&x); + | + +error[E0599]: no method named `method` found for unit type `()` in the current scope + --> $DIR/method-shadowed-by-trait.rs:117:13 + | +LL | x.foo().method(); + | --- ^^^^^^ method not found in `()` + | | + | this method is `a::T::foo` + | +note: this returns `()` + --> $DIR/method-shadowed-by-trait.rs:73:9 + | +LL | pub trait T { +LL | fn foo(&self) {} + | ^^^^^^^^^^^^^ +note: you might have meant to call `a::K::foo` instead + --> $DIR/method-shadowed-by-trait.rs:82:9 + | +LL | pub trait K

{ +LL | fn foo(&self) -> Other { Other { field : () } } + | ^^^^^^^^^^^^^^^^^^^^^^ +note: you might have meant to call `a::V::foo` instead + --> $DIR/method-shadowed-by-trait.rs:91:9 + | +LL | pub trait V { +LL | fn foo(&self) -> Other; + | ^^^^^^^^^^^^^^^^^^^^^^^ +note: you might have meant to call `S::foo` instead + --> $DIR/method-shadowed-by-trait.rs:64:5 + | +LL | impl S { +LL | fn foo(&self) -> Other { Other { field: () } } + | ^^^^^^^^^^^^^^^^^^^^^^ +help: consider calling `a::K::foo` using the fully-qualified path + | +LL - x.foo().method(); +LL + <_ as K<_>>::foo(&x).method(); + | +help: consider calling `a::V::foo` using the fully-qualified path + | +LL - x.foo().method(); +LL + <_ as V>::foo(&x).method(); + | +help: consider calling `S::foo` using the fully-qualified path + | +LL - x.foo().method(); +LL + S::foo(&x).method(); + | + +error[E0599]: no method named `method` found for unit type `()` in the current scope + --> $DIR/method-shadowed-by-trait.rs:120:15 + | +LL | let y = x.foo(); + | --- this method is `a::T::foo` +... +LL | let _ = y.method(); + | ^^^^^^ method not found in `()` + | +note: this returns `()` + --> $DIR/method-shadowed-by-trait.rs:73:9 + | +LL | pub trait T { +LL | fn foo(&self) {} + | ^^^^^^^^^^^^^ +note: you might have meant to call `a::K::foo` instead + --> $DIR/method-shadowed-by-trait.rs:82:9 + | +LL | pub trait K

{ +LL | fn foo(&self) -> Other { Other { field : () } } + | ^^^^^^^^^^^^^^^^^^^^^^ +note: you might have meant to call `a::V::foo` instead + --> $DIR/method-shadowed-by-trait.rs:91:9 + | +LL | pub trait V { +LL | fn foo(&self) -> Other; + | ^^^^^^^^^^^^^^^^^^^^^^^ +note: you might have meant to call `S::foo` instead + --> $DIR/method-shadowed-by-trait.rs:64:5 + | +LL | impl S { +LL | fn foo(&self) -> Other { Other { field: () } } + | ^^^^^^^^^^^^^^^^^^^^^^ +help: consider calling `a::K::foo` using the fully-qualified path + | +LL - let y = x.foo(); +LL + let y = <_ as K<_>>::foo(&x); + | +help: consider calling `a::V::foo` using the fully-qualified path + | +LL - let y = x.foo(); +LL + let y = <_ as V>::foo(&x); + | +help: consider calling `S::foo` using the fully-qualified path + | +LL - let y = x.foo(); +LL + let y = S::foo(&x); + | + +error: aborting due to 5 previous errors + +Some errors have detailed explanations: E0599, E0609. +For more information about an error, try `rustc --explain E0599`. diff --git a/tests/ui/methods/similar-method-out-of-scope-trait.rs b/tests/ui/methods/similar-method-out-of-scope-trait.rs new file mode 100644 index 0000000000000..3c97c34f2c6ac --- /dev/null +++ b/tests/ui/methods/similar-method-out-of-scope-trait.rs @@ -0,0 +1,88 @@ +// Regression test for #165389: don't suggest another method from the same missing trait. + +mod writer { + pub struct Writer; + + pub trait Write { + fn write(&self) {} + fn write_all(&self) {} + } + + impl Write for Writer {} + + impl Writer { + pub fn flush(&self) {} + } +} + +trait Read { + fn read(&self) {} +} + +impl Read for writer::Writer {} + +fn generic(writer: T) { + writer.writ(); + //~^ ERROR no method named `writ` found +} + +fn trait_object(writer: &dyn writer::Write) { + writer.writ(); + //~^ ERROR no method named `writ` found +} + +fn main() { + let writer = writer::Writer; + writer.write_all(); + //~^ ERROR no method named `write_all` found + writer.reed(); + //~^ ERROR no method named `reed` found + writer.flus(); + //~^ ERROR no method named `flus` found +} + +// A method from the missing trait must not hide a similarly named method that can be called. +mod hidden { + pub struct ByValue; + pub struct Ambiguous; + pub struct Inherent; + + pub trait Hidden { + fn method(&self) {} + fn method2(self) + where + Self: Sized, + { + } + } + + impl Hidden for ByValue {} + impl Hidden for Inherent {} + + pub trait HiddenRef { + fn method(&self) {} + fn method2(&self) {} + } + + impl HiddenRef for Ambiguous {} + + impl Inherent { + pub fn method2(&self) {} + } +} + +trait Visible { + fn method2(&self) {} +} + +impl Visible for hidden::ByValue {} +impl Visible for hidden::Ambiguous {} + +fn in_scope_candidates() { + hidden::ByValue.method(); + //~^ ERROR no method named `method` found + hidden::Ambiguous.method(); + //~^ ERROR no method named `method` found + hidden::Inherent.method(); + //~^ ERROR no method named `method` found +} diff --git a/tests/ui/methods/similar-method-out-of-scope-trait.stderr b/tests/ui/methods/similar-method-out-of-scope-trait.stderr new file mode 100644 index 0000000000000..02bad55825518 --- /dev/null +++ b/tests/ui/methods/similar-method-out-of-scope-trait.stderr @@ -0,0 +1,140 @@ +error[E0599]: no method named `writ` found for type parameter `T` in the current scope + --> $DIR/similar-method-out-of-scope-trait.rs:25:12 + | +LL | fn generic(writer: T) { + | - method `writ` not found for this type parameter +LL | writer.writ(); + | ^^^^ + | +help: there is a method `write` with a similar name + | +LL | writer.write(); + | + + +error[E0599]: no method named `writ` found for reference `&dyn writer::Write` in the current scope + --> $DIR/similar-method-out-of-scope-trait.rs:30:12 + | +LL | writer.writ(); + | ^^^^ + | +help: there is a method `write` with a similar name + | +LL | writer.write(); + | + + +error[E0599]: no method named `write_all` found for struct `Writer` in the current scope + --> $DIR/similar-method-out-of-scope-trait.rs:36:12 + | +LL | pub struct Writer; + | ----------------- method `write_all` not found for this struct +... +LL | fn write_all(&self) {} + | --------- the method is available for `Writer` here +... +LL | writer.write_all(); + | ^^^^^^^^^ method not found in `Writer` + | + = help: items from traits can only be used if the trait is in scope +help: trait `Write` which provides `write_all` is implemented but not in scope; perhaps you want to import it + | +LL + use crate::writer::Write; + | + +error[E0599]: no method named `reed` found for struct `Writer` in the current scope + --> $DIR/similar-method-out-of-scope-trait.rs:38:12 + | +LL | pub struct Writer; + | ----------------- method `reed` not found for this struct +... +LL | writer.reed(); + | ^^^^ + | +help: there is a method `read` with a similar name + | +LL - writer.reed(); +LL + writer.read(); + | + +error[E0599]: no method named `flus` found for struct `Writer` in the current scope + --> $DIR/similar-method-out-of-scope-trait.rs:40:12 + | +LL | pub struct Writer; + | ----------------- method `flus` not found for this struct +... +LL | writer.flus(); + | ^^^^ + | +help: there is a method `flush` with a similar name + | +LL | writer.flush(); + | + + +error[E0599]: no method named `method` found for struct `ByValue` in the current scope + --> $DIR/similar-method-out-of-scope-trait.rs:82:21 + | +LL | pub struct ByValue; + | ------------------ method `method` not found for this struct +... +LL | fn method(&self) {} + | ------ the method is available for `ByValue` here +... +LL | hidden::ByValue.method(); + | ^^^^^^ + | + = help: items from traits can only be used if the trait is in scope +help: trait `Hidden` which provides `method` is implemented but not in scope; perhaps you want to import it + | +LL + use crate::hidden::Hidden; + | +help: there is a method `method2` with a similar name + | +LL | hidden::ByValue.method2(); + | + + +error[E0599]: no method named `method` found for struct `Ambiguous` in the current scope + --> $DIR/similar-method-out-of-scope-trait.rs:84:23 + | +LL | pub struct Ambiguous; + | -------------------- method `method` not found for this struct +... +LL | fn method(&self) {} + | ------ the method is available for `Ambiguous` here +... +LL | hidden::Ambiguous.method(); + | ^^^^^^ + | + = help: items from traits can only be used if the trait is in scope +help: trait `HiddenRef` which provides `method` is implemented but not in scope; perhaps you want to import it + | +LL + use crate::hidden::HiddenRef; + | +help: there is a method `method2` with a similar name + | +LL | hidden::Ambiguous.method2(); + | + + +error[E0599]: no method named `method` found for struct `Inherent` in the current scope + --> $DIR/similar-method-out-of-scope-trait.rs:86:22 + | +LL | pub struct Inherent; + | ------------------- method `method` not found for this struct +... +LL | fn method(&self) {} + | ------ the method is available for `Inherent` here +... +LL | hidden::Inherent.method(); + | ^^^^^^ + | + = help: items from traits can only be used if the trait is in scope +help: trait `Hidden` which provides `method` is implemented but not in scope; perhaps you want to import it + | +LL + use crate::hidden::Hidden; + | +help: there is a method `method2` with a similar name + | +LL | hidden::Inherent.method2(); + | + + +error: aborting due to 8 previous errors + +For more information about this error, try `rustc --explain E0599`. diff --git a/tests/ui/pattern/rfc-3637-guard-patterns/borrow-check.rs b/tests/ui/pattern/rfc-3637-guard-patterns/borrow-check.rs new file mode 100644 index 0000000000000..2a30bcca100c1 --- /dev/null +++ b/tests/ui/pattern/rfc-3637-guard-patterns/borrow-check.rs @@ -0,0 +1,17 @@ +// Check whether the borrow checker runs in guard patterns + +#![feature(guard_patterns)] + +struct NonCopy(u8); + +pub fn probe( + (_ if const { + let x = NonCopy(0); + let y = x; + let z = x; + //~^ ERROR use of moved value: `x` [E0382] + true +}): u8, +) {} + +fn main() {} diff --git a/tests/ui/pattern/rfc-3637-guard-patterns/borrow-check.stderr b/tests/ui/pattern/rfc-3637-guard-patterns/borrow-check.stderr new file mode 100644 index 0000000000000..19a821e465ee5 --- /dev/null +++ b/tests/ui/pattern/rfc-3637-guard-patterns/borrow-check.stderr @@ -0,0 +1,22 @@ +error[E0382]: use of moved value: `x` + --> $DIR/borrow-check.rs:11:13 + | +LL | let x = NonCopy(0); + | - move occurs because `x` has type `NonCopy`, which does not implement the `Copy` trait +LL | let y = x; + | - value moved here +LL | let z = x; + | ^ value used here after move + | +note: if `NonCopy` implemented `Clone`, you could clone the value + --> $DIR/borrow-check.rs:5:1 + | +LL | struct NonCopy(u8); + | ^^^^^^^^^^^^^^ consider implementing `Clone` for this type +... +LL | let y = x; + | - you could clone this value + +error: aborting due to 1 previous error + +For more information about this error, try `rustc --explain E0382`. diff --git a/tests/ui/pattern/rfc-3637-guard-patterns/closure.rs b/tests/ui/pattern/rfc-3637-guard-patterns/closure.rs new file mode 100644 index 0000000000000..186842fb860cc --- /dev/null +++ b/tests/ui/pattern/rfc-3637-guard-patterns/closure.rs @@ -0,0 +1,8 @@ +// checks whether closures work in guard patterns + +//@ check-pass +#![feature(guard_patterns)] + +pub fn probe((_ if (|| true)()): u8) {} + +fn main() {} diff --git a/tests/ui/privacy/privacy-in-params.rs b/tests/ui/privacy/privacy-in-params.rs new file mode 100644 index 0000000000000..aa95d3a85baa6 --- /dev/null +++ b/tests/ui/privacy/privacy-in-params.rs @@ -0,0 +1,22 @@ +// Checks whether privacy of fields is checked in parameters + +mod hidden { + pub struct Record { secret: u8 } +} + +fn leak(hidden::Record { secret }: hidden::Record) -> u8 { + //~^ ERROR field `secret` of struct `Record` is private + secret +} + +fn f() -> [u8; { let _ = hidden::Record { secret: 1 }; 0 }] { + //~^ ERROR field `secret` of struct `Record` is private + [] +} + +trait Test { + fn trait_method() -> [u8; { let _ = hidden::Record { secret: 1 }; 0 }]; + //~^ ERROR field `secret` of struct `Record` is private +} + +fn main() {} diff --git a/tests/ui/privacy/privacy-in-params.stderr b/tests/ui/privacy/privacy-in-params.stderr new file mode 100644 index 0000000000000..eec757c1c84b5 --- /dev/null +++ b/tests/ui/privacy/privacy-in-params.stderr @@ -0,0 +1,21 @@ +error[E0451]: field `secret` of struct `Record` is private + --> $DIR/privacy-in-params.rs:7:26 + | +LL | fn leak(hidden::Record { secret }: hidden::Record) -> u8 { + | ^^^^^^ private field + +error[E0451]: field `secret` of struct `Record` is private + --> $DIR/privacy-in-params.rs:12:43 + | +LL | fn f() -> [u8; { let _ = hidden::Record { secret: 1 }; 0 }] { + | ^^^^^^ private field + +error[E0451]: field `secret` of struct `Record` is private + --> $DIR/privacy-in-params.rs:18:58 + | +LL | fn trait_method() -> [u8; { let _ = hidden::Record { secret: 1 }; 0 }]; + | ^^^^^^ private field + +error: aborting due to 3 previous errors + +For more information about this error, try `rustc --explain E0451`. diff --git a/tests/ui/suggestions/import-visible-path-39175.stderr b/tests/ui/suggestions/import-visible-path-39175.stderr index 0b558ca4b52b1..a758a18f331d3 100644 --- a/tests/ui/suggestions/import-visible-path-39175.stderr +++ b/tests/ui/suggestions/import-visible-path-39175.stderr @@ -2,11 +2,9 @@ error[E0599]: no method named `exec` found for mutable reference `&mut Command` --> $DIR/import-visible-path-39175.rs:13:47 | LL | let _ = Command::new("echo").arg("hello").exec(); - | ^^^^ + | ^^^^ method not found in `&mut Command` | = help: items from traits can only be used if the trait is in scope -help: there is a method `pre_exec` with a similar name, but with different arguments - --> $SRC_DIR/std/src/os/unix/process.rs:LL:COL help: trait `CommandExt` which provides `exec` is implemented but not in scope; perhaps you want to import it | LL + use std::os::unix::process::CommandExt; diff --git a/tests/ui/tool-attributes/auxiliary/reflecting.rs b/tests/ui/tool-attributes/auxiliary/reflecting.rs new file mode 100644 index 0000000000000..1c5d317266fab --- /dev/null +++ b/tests/ui/tool-attributes/auxiliary/reflecting.rs @@ -0,0 +1,9 @@ +#![feature(register_tool)] +#![feature(type_info)] + +#![register_tool(aaa)] +#![register_tool(bbb(reflect))] + +#[aaa::aa] +#[bbb::bb] +pub struct A; diff --git a/tests/ui/tool-attributes/invalid-tool.stderr b/tests/ui/tool-attributes/invalid-tool.stderr index b0ee674b4086d..9833bd2b525a1 100644 --- a/tests/ui/tool-attributes/invalid-tool.stderr +++ b/tests/ui/tool-attributes/invalid-tool.stderr @@ -9,7 +9,7 @@ LL | #![register_tool(1)] help: must be of the form | LL - #![register_tool(1)] -LL + #![register_tool(tool1, tool2, ...)] +LL + #![register_tool(tool1, tool2(reflect), ...)] | error: expected identifier, found reserved identifier `_` @@ -29,7 +29,7 @@ LL | #![register_tool(_)] help: must be of the form | LL - #![register_tool(_)] -LL + #![register_tool(tool1, tool2, ...)] +LL + #![register_tool(tool1, tool2(reflect), ...)] | error[E0565]: malformed `register_tool` attribute input @@ -43,7 +43,7 @@ LL | #![register_tool(crate)] help: must be of the form | LL - #![register_tool(crate)] -LL + #![register_tool(tool1, tool2, ...)] +LL + #![register_tool(tool1, tool2(reflect), ...)] | error[E0565]: malformed `register_tool` attribute input @@ -57,7 +57,7 @@ LL | #![register_tool(self)] help: must be of the form | LL - #![register_tool(self)] -LL + #![register_tool(tool1, tool2, ...)] +LL + #![register_tool(tool1, tool2(reflect), ...)] | error[E0565]: malformed `register_tool` attribute input @@ -71,7 +71,7 @@ LL | #![register_tool(Self)] help: must be of the form | LL - #![register_tool(Self)] -LL + #![register_tool(tool1, tool2, ...)] +LL + #![register_tool(tool1, tool2(reflect), ...)] | error[E0565]: malformed `register_tool` attribute input @@ -85,7 +85,7 @@ LL | #![register_tool(super)] help: must be of the form | LL - #![register_tool(super)] -LL + #![register_tool(tool1, tool2, ...)] +LL + #![register_tool(tool1, tool2(reflect), ...)] | error: aborting due to 7 previous errors diff --git a/tests/ui/tool-attributes/nested-disallowed.stderr b/tests/ui/tool-attributes/nested-disallowed.stderr index eaa5d60ba9728..89aa869ec4d51 100644 --- a/tests/ui/tool-attributes/nested-disallowed.stderr +++ b/tests/ui/tool-attributes/nested-disallowed.stderr @@ -9,7 +9,7 @@ LL | #![register_tool(foo::bar)] help: must be of the form | LL - #![register_tool(foo::bar)] -LL + #![register_tool(tool1, tool2, ...)] +LL + #![register_tool(tool1, tool2(reflect), ...)] | error: aborting due to 1 previous error diff --git a/tests/ui/tool-attributes/register_reflected_tool.rs b/tests/ui/tool-attributes/register_reflected_tool.rs new file mode 100644 index 0000000000000..6d289f5c6667e --- /dev/null +++ b/tests/ui/tool-attributes/register_reflected_tool.rs @@ -0,0 +1,55 @@ +//@ aux-crate: dep=reflecting.rs +//@ compile-flags: -Zcrate-attr=register_tool(jjj(reflect)) + +#![feature(register_tool)] +#![feature(type_info)] + +#![feature(const_trait_impl)] +#![feature(const_cmp)] + +#![register_tool(aaa(reflect))] +#![register_tool(bbb)] +#![register_tool(ccc(reflect::c))] //~ ERROR unrecognized tool option `reflect::c` +#![register_tool(ddd(mrow))] //~ ERROR unrecognized tool option `mrow` +#![register_tool(eee(reflect, reflect))] //~ ERROR malformed `register_tool` attribute input +#![register_tool(fff(mrow, reflect))] //~ ERROR malformed `register_tool` attribute input + +#![register_tool(ggg)] +#![register_tool(ggg(reflect))] //~ ERROR duplicate tool `ggg` registered + +#![register_tool(hhh(reflect))] +#![register_tool(hhh)] //~ ERROR duplicate tool `hhh` registered + + + +#![register_tool(clippy(reflect), rustfmt(reflect))] +//~^ ERROR the tool attribute `clippy` is predefined and cannot be marked as being available for reflection +//~| ERROR the tool attribute `rustfmt` is predefined and cannot be marked as being available for reflection +#![register_tool(diagnostic(reflect), miri(reflect), rust_analyzer(reflect))] +//~^ ERROR the tool attribute `diagnostic` is predefined and cannot be marked as being available for reflection +//~| ERROR the tool attribute `miri` is predefined and cannot be marked as being available for reflection +//~| ERROR the tool attribute `rust_analyzer` is predefined and cannot be marked as being available for reflection + +use std::any::TypeId; + +#[aaa::aa] +#[bbb::bb] +#[hhh::hh] +#[ggg::gg] +#[jjj::jj] +#[clippy::a] +#[rustfmt::a] +#[diagnostic::a] +//~^ WARN unknown diagnostic attribute +#[miri::a] +#[rust_analyzer::a] +struct A; + +const _: () = assert!( TypeId::of::().reflected_attrs() == + ["#[aaa::aa]", "#[hhh::hh]", "#[ggg::gg]", "#[jjj::jj]"] ); + +// test cross crate encoding of reflectivity +const _: () = assert!( TypeId::of::().reflected_attrs() == &["#[bbb::bb]"]); + + +fn main() {} diff --git a/tests/ui/tool-attributes/register_reflected_tool.stderr b/tests/ui/tool-attributes/register_reflected_tool.stderr new file mode 100644 index 0000000000000..e7dccdc439d51 --- /dev/null +++ b/tests/ui/tool-attributes/register_reflected_tool.stderr @@ -0,0 +1,99 @@ +error: unrecognized tool option `reflect::c` + --> $DIR/register_reflected_tool.rs:12:22 + | +LL | #![register_tool(ccc(reflect::c))] + | ^^^^^^^^^^ + +error: unrecognized tool option `mrow` + --> $DIR/register_reflected_tool.rs:13:22 + | +LL | #![register_tool(ddd(mrow))] + | ^^^^ + +error[E0805]: malformed `register_tool` attribute input + --> $DIR/register_reflected_tool.rs:14:4 + | +LL | #![register_tool(eee(reflect, reflect))] + | ^^^^^^^^^^^^^^^^^------------------^ + | | + | expected a single argument here + | +help: must be of the form + | +LL - #![register_tool(eee(reflect, reflect))] +LL + #![register_tool(tool1, tool2(reflect), ...)] + | + +error[E0805]: malformed `register_tool` attribute input + --> $DIR/register_reflected_tool.rs:15:4 + | +LL | #![register_tool(fff(mrow, reflect))] + | ^^^^^^^^^^^^^^^^^---------------^ + | | + | expected a single argument here + | +help: must be of the form + | +LL - #![register_tool(fff(mrow, reflect))] +LL + #![register_tool(tool1, tool2(reflect), ...)] + | + +error: the tool attribute `clippy` is predefined and cannot be marked as being available for reflection + --> $DIR/register_reflected_tool.rs:25:18 + | +LL | #![register_tool(clippy(reflect), rustfmt(reflect))] + | ^^^^^^^^^^^^^^^ + +error: the tool attribute `rustfmt` is predefined and cannot be marked as being available for reflection + --> $DIR/register_reflected_tool.rs:25:35 + | +LL | #![register_tool(clippy(reflect), rustfmt(reflect))] + | ^^^^^^^^^^^^^^^^ + +error: the tool attribute `diagnostic` is predefined and cannot be marked as being available for reflection + --> $DIR/register_reflected_tool.rs:28:18 + | +LL | #![register_tool(diagnostic(reflect), miri(reflect), rust_analyzer(reflect))] + | ^^^^^^^^^^^^^^^^^^^ + +error: the tool attribute `miri` is predefined and cannot be marked as being available for reflection + --> $DIR/register_reflected_tool.rs:28:39 + | +LL | #![register_tool(diagnostic(reflect), miri(reflect), rust_analyzer(reflect))] + | ^^^^^^^^^^^^^ + +error: the tool attribute `rust_analyzer` is predefined and cannot be marked as being available for reflection + --> $DIR/register_reflected_tool.rs:28:54 + | +LL | #![register_tool(diagnostic(reflect), miri(reflect), rust_analyzer(reflect))] + | ^^^^^^^^^^^^^^^^^^^^^^ + +error: duplicate tool `ggg` registered + --> $DIR/register_reflected_tool.rs:18:18 + | +LL | #![register_tool(ggg)] + | --- already registered here +LL | #![register_tool(ggg(reflect))] + | ^^^ + | + = note: `#[deny(duplicate_tools)]` on by default + +error: duplicate tool `hhh` registered + --> $DIR/register_reflected_tool.rs:21:18 + | +LL | #![register_tool(hhh(reflect))] + | --- already registered here +LL | #![register_tool(hhh)] + | ^^^ + +warning: unknown diagnostic attribute + --> $DIR/register_reflected_tool.rs:42:15 + | +LL | #[diagnostic::a] + | ^ + | + = note: `#[warn(unknown_diagnostic_attributes)]` (part of `#[warn(unknown_or_malformed_diagnostic_attributes)]`) on by default + +error: aborting due to 11 previous errors; 1 warning emitted + +For more information about this error, try `rustc --explain E0805`. diff --git a/tests/ui/trait-bounds/wf-check-c-variadics.rs b/tests/ui/trait-bounds/wf-check-c-variadics.rs new file mode 100644 index 0000000000000..463f019f604d8 --- /dev/null +++ b/tests/ui/trait-bounds/wf-check-c-variadics.rs @@ -0,0 +1,12 @@ +// In `hir_wf_check.rs` we try to find the innermost type that is not well formed, +// so we can give the user an accurate span. +// This test checks if this happens correctly for c-variadics. + +struct NeedsCopy(T); + +unsafe extern "C" { + fn f(x: i32, ...) -> Option>; + //~^ ERROR the trait bound `String: Copy` is not satisfied +} + +fn main() {} diff --git a/tests/ui/trait-bounds/wf-check-c-variadics.stderr b/tests/ui/trait-bounds/wf-check-c-variadics.stderr new file mode 100644 index 0000000000000..8aaf40469dc72 --- /dev/null +++ b/tests/ui/trait-bounds/wf-check-c-variadics.stderr @@ -0,0 +1,15 @@ +error[E0277]: the trait bound `String: Copy` is not satisfied + --> $DIR/wf-check-c-variadics.rs:8:33 + | +LL | fn f(x: i32, ...) -> Option>; + | ^^^^^^^^^^^^^^^^^ the trait `Copy` is not implemented for `String` + | +note: required by a bound in `NeedsCopy` + --> $DIR/wf-check-c-variadics.rs:5:21 + | +LL | struct NeedsCopy(T); + | ^^^^ required by this bound in `NeedsCopy` + +error: aborting due to 1 previous error + +For more information about this error, try `rustc --explain E0277`.