diff --git a/Cargo.lock b/Cargo.lock index 75389f90ad62a..b555b2cfe6a55 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -3924,6 +3924,7 @@ dependencies = [ name = "rustc_crate_store" version = "0.0.0" dependencies = [ + "bitflags", "rustc_abi", "rustc_attr_ir", "rustc_data_structures", diff --git a/compiler/rustc_abi/src/callconv/reg.rs b/compiler/rustc_abi/src/callconv/reg.rs index dda7a45f9c2b7..393ec3801f577 100644 --- a/compiler/rustc_abi/src/callconv/reg.rs +++ b/compiler/rustc_abi/src/callconv/reg.rs @@ -76,8 +76,7 @@ impl Reg { let dl = cx.data_layout(); match self.kind { RegKind::Integer => match self.size.bits() { - 1 => dl.i1_align, - 2..=8 => dl.i8_align, + 1..=8 => Align::ONE, 9..=16 => dl.i16_align, 17..=32 => dl.i32_align, 33..=64 => dl.i64_align, diff --git a/compiler/rustc_abi/src/layout.rs b/compiler/rustc_abi/src/layout.rs index dd8652a05faab..720efd43dd248 100644 --- a/compiler/rustc_abi/src/layout.rs +++ b/compiler/rustc_abi/src/layout.rs @@ -365,7 +365,7 @@ impl LayoutCalculator { Some(present_first) => present_first, // Uninhabited because it has no variants, or only absent ones. None if is_enum => { - return Ok(LayoutData::never_type(&self.cx)); + return Ok(LayoutData::never_type()); } // If it's a struct, still compute a layout so that we can still compute the // field offsets. @@ -412,7 +412,7 @@ impl LayoutCalculator { F: Deref> + fmt::Debug + Copy, { let dl = self.cx.data_layout(); - let mut align = if repr.pack.is_some() { dl.i8_align } else { dl.aggregate_align }; + let mut align = if repr.pack.is_some() { Align::ONE } else { dl.aggregate_align }; let mut max_repr_align = repr.align; // If all the non-ZST fields have the same repr and union repr optimizations aren't @@ -601,7 +601,7 @@ impl LayoutCalculator { { let dl = self.cx.data_layout(); let pack = repr.pack; - let mut align = if pack.is_some() { dl.i8_align } else { dl.aggregate_align }; + let mut align = if pack.is_some() { Align::ONE } else { dl.aggregate_align }; let mut max_repr_align = repr.align; let mut in_memory_order: IndexVec = fields.indices().collect(); let optimize_field_order = !repr.inhibit_struct_field_reordering(); diff --git a/compiler/rustc_abi/src/layout/simple.rs b/compiler/rustc_abi/src/layout/simple.rs index f16daccc3c526..dff1f9ee44980 100644 --- a/compiler/rustc_abi/src/layout/simple.rs +++ b/compiler/rustc_abi/src/layout/simple.rs @@ -4,13 +4,13 @@ use rustc_hashes::Hash64; use rustc_index::{Idx, IndexVec}; use crate::{ - BackendRepr, FieldsShape, HasDataLayout, LayoutData, Niche, Primitive, Scalar, Size, Variants, + Align, BackendRepr, FieldsShape, HasDataLayout, LayoutData, Niche, Primitive, Scalar, Size, + Variants, }; /// "Simple" layout constructors that cannot fail. impl LayoutData { - pub fn unit(cx: &C, sized: bool) -> Self { - let dl = cx.data_layout(); + pub fn unit(sized: bool) -> Self { LayoutData { variants: Variants::Single { index: VariantIdx::new(0) }, fields: FieldsShape::Arbitrary { @@ -20,17 +20,16 @@ impl LayoutData { backend_repr: BackendRepr::Memory { sized }, largest_niche: None, uninhabited: false, - align: dl.i8_align, + align: Align::ONE, size: Size::ZERO, max_repr_align: None, - unadjusted_abi_align: dl.i8_align, + unadjusted_abi_align: Align::ONE, repr_c: false, randomization_seed: Hash64::new(0), } } - pub fn never_type(cx: &C) -> Self { - let dl = cx.data_layout(); + pub fn never_type() -> Self { // This is also used for uninhabited enums, so we use `Variants::Empty`. LayoutData { variants: Variants::Empty, @@ -38,10 +37,10 @@ impl LayoutData { backend_repr: BackendRepr::Memory { sized: true }, largest_niche: None, uninhabited: true, - align: dl.i8_align, + align: Align::ONE, size: Size::ZERO, max_repr_align: None, - unadjusted_abi_align: dl.i8_align, + unadjusted_abi_align: Align::ONE, repr_c: false, randomization_seed: Hash64::ZERO, } @@ -128,8 +127,7 @@ impl LayoutData { /// /// Uninhabited variants get pruned as part of the layout calculation, /// so this can be used after the fact to reconstitute a layout. - pub fn uninhabited_variant(cx: &C, index: VariantIdx, fields: usize) -> Self { - let dl = cx.data_layout(); + pub fn uninhabited_variant(index: VariantIdx, fields: usize) -> Self { LayoutData { variants: Variants::Single { index }, fields: match NonZero::new(fields) { @@ -142,10 +140,10 @@ impl LayoutData { backend_repr: BackendRepr::Memory { sized: true }, largest_niche: None, uninhabited: true, - align: dl.i8_align, + align: Align::ONE, size: Size::ZERO, max_repr_align: None, - unadjusted_abi_align: dl.i8_align, + unadjusted_abi_align: Align::ONE, repr_c: false, // Variant layouts never flow back into actual layout computations, // so dummy values are fine here. diff --git a/compiler/rustc_abi/src/lib.rs b/compiler/rustc_abi/src/lib.rs index 6d02f91ff7396..1f2fcfc389f2c 100644 --- a/compiler/rustc_abi/src/lib.rs +++ b/compiler/rustc_abi/src/lib.rs @@ -318,8 +318,6 @@ pub struct PointerSpec { #[derive(Debug, PartialEq, Eq)] pub struct TargetDataLayout { pub endian: Endian, - pub i1_align: Align, - pub i8_align: Align, pub i16_align: Align, pub i32_align: Align, pub i64_align: Align, @@ -359,8 +357,6 @@ impl Default for TargetDataLayout { let align = |bits| Align::from_bits(bits).unwrap(); TargetDataLayout { endian: Endian::Big, - i1_align: align(8), - i8_align: align(8), i16_align: align(16), i32_align: align(32), i64_align: align(32), @@ -394,6 +390,7 @@ pub enum TargetDataLayoutError<'a> { InvalidBits { kind: &'a str, bit: &'a str, cause: &'a str, err: ParseIntError }, MissingAlignment { cause: &'a str }, InvalidAlignment { cause: &'a str, err: AlignFromBytesError }, + AlignmentTooLargeForType { cause: &'a str, align: Align }, InconsistentTargetArchitecture { dl: &'a str, target: &'a str }, InconsistentTargetPointerWidth { pointer_size: u64, target: u16 }, InvalidBitsSize { err: String }, @@ -426,6 +423,9 @@ impl Diagnostic<'_> for TargetDataLayoutError<'_> { .with_arg("cause", cause) .with_arg("err", err.to_string()) } + TargetDataLayoutError::AlignmentTooLargeForType { cause, align } => { + Diag::new(dcx, level, msg!("alignment of `{$align}` bytes in \"data-layout\" is too large for `{$cause}`")).with_arg("align", align.bytes()).with_arg("cause", cause) + } TargetDataLayoutError::InconsistentTargetArchitecture { dl, target } => { Diag::new(dcx, level, msg!("inconsistent target specification: \"data-layout\" claims architecture is {$dl}-endian, while \"target-endian\" is `{$target}`")) .with_arg("dl", dl).with_arg("target", target) @@ -477,22 +477,28 @@ impl TargetDataLayout { |s: &'a str, cause: &'a str| parse_bits(s, "size", cause).map(Size::from_bits); // Parse an alignment string. - let parse_align_str = |s: &'a str, cause: &'a str| { + let parse_align_str = |s: &'a str, cause: &'a str, size_bits: u64| { let align_from_bits = |bits| { Align::from_bits(bits) .map_err(|err| TargetDataLayoutError::InvalidAlignment { cause, err }) }; - let abi = parse_bits(s, "alignment", cause)?; - Ok(align_from_bits(abi)?) + let align_bits = parse_bits(s, "alignment", cause)?; + let align = align_from_bits(align_bits)?; + let max_align_bytes = size_bits.div_ceil(8).next_power_of_two(); + if align.bytes() > max_align_bytes { + Err(TargetDataLayoutError::AlignmentTooLargeForType { cause, align }) + } else { + Ok(align) + } }; // Parse an alignment sequence, possibly in the form `[:]`, // ignoring the secondary alignment specifications. - let parse_align_seq = |s: &[&'a str], cause: &'a str| { + let parse_align_seq = |s: &[&'a str], cause: &'a str, size_bits: u64| { if s.is_empty() { return Err(TargetDataLayoutError::MissingAlignment { cause }); } - parse_align_str(s[0], cause) + parse_align_str(s[0], cause, size_bits) }; let mut dl = TargetDataLayout::default(); @@ -508,12 +514,12 @@ impl TargetDataLayout { [p] if p.starts_with('P') => { dl.instruction_address_space = parse_address_space(&p[1..], "P")? } - ["a", a @ ..] => dl.aggregate_align = parse_align_seq(a, "a")?, - ["f16", a @ ..] => dl.f16_align = parse_align_seq(a, "f16")?, - ["f32", a @ ..] => dl.f32_align = parse_align_seq(a, "f32")?, - ["f64", a @ ..] => dl.f64_align = parse_align_seq(a, "f64")?, - ["f80", a @ ..] => dl.x87_f80_align = parse_align_seq(a, "f80")?, - ["f128", a @ ..] => dl.f128_align = parse_align_seq(a, "f128")?, + ["a", a @ ..] => dl.aggregate_align = parse_align_seq(a, "a", u64::MAX)?, + ["f16", a @ ..] => dl.f16_align = parse_align_seq(a, "f16", 16)?, + ["f32", a @ ..] => dl.f32_align = parse_align_seq(a, "f32", 32)?, + ["f64", a @ ..] => dl.f64_align = parse_align_seq(a, "f64", 64)?, + ["f80", a @ ..] => dl.x87_f80_align = parse_align_seq(a, "f80", 80)?, + ["f128", a @ ..] => dl.f128_align = parse_align_seq(a, "f128", 128)?, [p, s, a @ ..] if p.starts_with("p") => { let mut p = p.strip_prefix('p').unwrap(); let mut _is_fat = false; @@ -541,7 +547,7 @@ impl TargetDataLayout { }; let pointer_size = parse_size(s, "p-")?; - let pointer_align = parse_align_seq(a, "p-")?; + let pointer_align = parse_align_seq(a, "p-", pointer_size.bits())?; let info = PointerSpec { pointer_offset: pointer_size, pointer_size, @@ -585,9 +591,10 @@ impl TargetDataLayout { AddressSpace::ZERO }; + let pointer_size = parse_size(s, "p-")?; let info = PointerSpec { - pointer_size: parse_size(s, "p-")?, - pointer_align: parse_align_str(a, "p-")?, + pointer_size, + pointer_align: parse_align_str(a, "p-", pointer_size.bits())?, pointer_offset: parse_size(i, "p-")?, _is_fat, }; @@ -609,10 +616,10 @@ impl TargetDataLayout { parse_size(&s[1..], "i")?; // For the user error. continue; }; - let a = parse_align_seq(a, s)?; + let a = parse_align_seq(a, s, bits)?; match bits { - 1 => dl.i1_align = a, - 8 => dl.i8_align = a, + // i1 and i8 always have an alignment of 1 byte - this has already been + // checked by `parse_align_seq` above. 16 => dl.i16_align = a, 32 => dl.i32_align = a, 64 => dl.i64_align = a, @@ -627,7 +634,7 @@ impl TargetDataLayout { } [s, a @ ..] if s.starts_with('v') => { let v_size = parse_size(&s[1..], "v")?; - let a = parse_align_seq(a, s)?; + let a = parse_align_seq(a, s, v_size.bits())?; if let Some(v) = dl.vector_align.iter_mut().find(|v| v.0 == v_size) { v.1 = a; continue; @@ -1280,7 +1287,7 @@ impl Integer { let dl = cx.data_layout(); match self { - I8 => dl.i8_align, + I8 => Align::ONE, I16 => dl.i16_align, I32 => dl.i32_align, I64 => dl.i64_align, diff --git a/compiler/rustc_ast/src/ast.rs b/compiler/rustc_ast/src/ast.rs index 8338df0c46e8f..a8a18a0742fde 100644 --- a/compiler/rustc_ast/src/ast.rs +++ b/compiler/rustc_ast/src/ast.rs @@ -354,7 +354,7 @@ impl From for Box { pub struct ParenthesizedArgs { /// ```text /// Foo(A, B) -> C - /// ^^^^^^^^^^^^^^ + /// ^^^^^^^^^^^ /// ``` pub span: Span, @@ -3556,17 +3556,6 @@ impl GeneratedAttr { } } - pub fn is_word(&self) -> bool { - match self { - GeneratedAttr::AutomaticallyDerived => true, - GeneratedAttr::RustcConstUnstableDerived => false, - GeneratedAttr::Inline => true, - GeneratedAttr::DocHidden => false, - GeneratedAttr::CoverageOff => false, - GeneratedAttr::RustcTestMarker(_) => false, - GeneratedAttr::RustcTrivialFieldReads => false, - } - } pub fn value_str(&self) -> Option { match self { GeneratedAttr::AutomaticallyDerived => None, diff --git a/compiler/rustc_ast/src/attr/mod.rs b/compiler/rustc_ast/src/attr/mod.rs index 185650489fb32..92ed584076c97 100644 --- a/compiler/rustc_ast/src/attr/mod.rs +++ b/compiler/rustc_ast/src/attr/mod.rs @@ -8,7 +8,6 @@ use std::sync::atomic::{AtomicU32, Ordering}; use rustc_index::bit_set::GrowableBitSet; use rustc_span::{Ident, Span, Symbol, sym}; -use smallvec::{SmallVec, smallvec}; use thin_vec::{ThinVec, thin_vec}; use crate::ast::{ @@ -135,15 +134,6 @@ impl Attribute { } } - pub fn meta_kind(&self) -> Option { - match &self.kind { - AttrKind::Normal(normal) => normal.item.meta_kind(), - AttrKind::Synthetic(..) => unreachable!(), - AttrKind::DocComment(..) => None, - AttrKind::Generated(..) => None, - } - } - pub fn append_token_trees_to(&self, res: &mut Vec) { match &self.kind { AttrKind::Normal(normal) => normal @@ -202,15 +192,6 @@ impl Attribute { AttrKind::Synthetic(..) | AttrKind::DocComment(..) | AttrKind::Generated(..) => None, } } - - pub fn path_span(&self) -> Option { - match &self.kind { - AttrKind::Normal(attr) => Some(attr.item.path.span), - AttrKind::Synthetic(..) => unreachable!(), - AttrKind::DocComment(_, _) => None, - AttrKind::Generated(generated) => generated.path_span(), - } - } } impl AttrItem { @@ -282,6 +263,11 @@ impl AttrItem { pub fn meta_kind(&self) -> Option { MetaItemKind::from_attr_args(&self.args) } + + /// Returns whether the attribute is a path, without any arguments. + pub fn is_word(&self) -> bool { + matches!(self.args, AttrArgs::Empty) + } } impl MetaItem { @@ -891,30 +877,6 @@ impl Attribute { names.iter().any(|&name| self.has_name(name)) } - /// Returns whether the attribute is a path, without any arguments. - pub fn is_word(&self) -> bool { - match &self.kind { - AttrKind::Normal(normal) => matches!(normal.item.args, AttrArgs::Empty), - AttrKind::Synthetic(..) => unreachable!(), - AttrKind::DocComment(..) => false, - AttrKind::Generated(generated) => generated.is_word(), - } - } - - pub fn path(&self) -> SmallVec<[Symbol; 1]> { - use SyntheticAttr::*; - match &self.kind { - AttrKind::Normal(normal) => { - normal.item.path.segments.iter().map(|i| i.ident.name).collect() - } - AttrKind::Synthetic(CfgTrace(_)) => smallvec![sym::cfg], - AttrKind::Synthetic(CfgAttrTrace(_)) => smallvec![sym::cfg_attr], - AttrKind::Synthetic(TestEntrypoint) => smallvec![], - AttrKind::DocComment(_, _) => smallvec![sym::doc], - AttrKind::Generated(generated) => generated.path().iter().copied().collect(), - } - } - /// Returns the documentation if this is a doc comment or a sugared doc comment. /// * `///doc` returns `Some("doc")`. /// * `#[doc = "doc"]` returns `Some("doc")`. diff --git a/compiler/rustc_ast_lowering/src/item.rs b/compiler/rustc_ast_lowering/src/item.rs index bbbabf75d0805..900fbac6b2356 100644 --- a/compiler/rustc_ast_lowering/src/item.rs +++ b/compiler/rustc_ast_lowering/src/item.rs @@ -1326,7 +1326,8 @@ impl<'hir> LoweringContext<'_, 'hir> { // create a fake body so that the entire rest of the compiler doesn't have to deal with // this as a special case. return self.lower_fn_body(decl, contract, |this| { - if find_attr!(attrs, RustcIntrinsic) || this.tcx.is_sdylib_interface_build() { + if find_attr!(attrs, RustcIntrinsic { .. }) || this.tcx.is_sdylib_interface_build() + { let span = this.lower_span(span); let empty_block = hir::Block { hir_id: this.next_id(), diff --git a/compiler/rustc_ast_lowering/src/lib.rs b/compiler/rustc_ast_lowering/src/lib.rs index 53896b05d87c0..ae6bdd15853bc 100644 --- a/compiler/rustc_ast_lowering/src/lib.rs +++ b/compiler/rustc_ast_lowering/src/lib.rs @@ -1311,7 +1311,7 @@ impl<'hir> LoweringContext<'_, 'hir> { args: Default::default(), constraints: &[], parenthesized: hir::GenericArgsParentheses::ReturnTypeNotation, - span: data.span, + span: constraint.ident.span.to(data.span), } } else { let guar = self.emit_bad_parenthesized_trait_in_assoc_ty(data); diff --git a/compiler/rustc_ast_lowering/src/path.rs b/compiler/rustc_ast_lowering/src/path.rs index 49ad9ea4a98a1..61baf6b8d9d04 100644 --- a/compiler/rustc_ast_lowering/src/path.rs +++ b/compiler/rustc_ast_lowering/src/path.rs @@ -318,6 +318,7 @@ impl<'hir> LoweringContext<'_, 'hir> { GenericArgsMode::ParenSugar | GenericArgsMode::Silence => self .lower_parenthesized_parameter_data( data, + segment.span(), itctx, bound_modifier_allowed_features, hir_id, @@ -347,7 +348,7 @@ impl<'hir> LoweringContext<'_, 'hir> { }; let guar = self .dcx() - .emit_err(GenericTypeWithParentheses { span: data.span, sub }); + .emit_err(GenericTypeWithParentheses { span: segment.span(), sub }); ( self.lower_angle_bracketed_parameter_data( &data.as_angle_bracketed_args(), @@ -509,6 +510,7 @@ impl<'hir> LoweringContext<'_, 'hir> { fn lower_parenthesized_parameter_data( &mut self, data: &ParenthesizedArgs, + segment_span: Span, itctx: ImplTraitContext, bound_modifier_allowed_features: Option>, segment_hir_id: HirId, @@ -518,7 +520,7 @@ impl<'hir> LoweringContext<'_, 'hir> { // a hidden lifetime parameter. This is needed for backwards // compatibility, even in contexts like an impl header where // we generally don't permit such things (see #51008). - let ParenthesizedArgs { span, inputs, inputs_span, output } = data; + let ParenthesizedArgs { span: _, inputs, inputs_span, output } = data; // FIXME uses the segments HIR id which is not correct, it should // be the parameters HIR id instead. This is currently not lowered. @@ -550,7 +552,7 @@ impl<'hir> LoweringContext<'_, 'hir> { } FnRetTy::Ty(ty) => self .lower_ty_alloc(ty, ImplTraitContext::Disallowed(ImplTraitPosition::FnTraitReturn)), - FnRetTy::Default(_) => self.arena.alloc(self.ty_tup(*span, &[])), + FnRetTy::Default(_) => self.arena.alloc(self.ty_tup(segment_span, &[])), }; let args = smallvec![GenericArg::Type( self.arena.alloc(self.ty_tup(*inputs_span, inputs)).try_as_ambig_ty().unwrap() diff --git a/compiler/rustc_ast_passes/src/ast_validation.rs b/compiler/rustc_ast_passes/src/ast_validation.rs index b8dc84f76c3ef..20c09d34bb98c 100644 --- a/compiler/rustc_ast_passes/src/ast_validation.rs +++ b/compiler/rustc_ast_passes/src/ast_validation.rs @@ -1908,10 +1908,10 @@ impl Visitor<'_> for AstValidator<'_> { } } // The lowered form of parenthesized generic args contains an associated type binding. - Some(ast::GenericArgs::Parenthesized(args)) => { + Some(ast::GenericArgs::Parenthesized(_)) => { self.dcx().emit_err( diagnostics::NegativeBoundWithParentheticalNotation { - span: args.span, + span: segment.span(), }, ); } diff --git a/compiler/rustc_ast_passes/src/show_spans.rs b/compiler/rustc_ast_passes/src/show_spans.rs index b28535653b0ed..6e2ff11c5fd4b 100644 --- a/compiler/rustc_ast_passes/src/show_spans.rs +++ b/compiler/rustc_ast_passes/src/show_spans.rs @@ -1,3 +1,5 @@ +use std::mem; + use rustc_ast::visit::{self, Visitor}; use rustc_ast::{self as ast, ItemKind}; use rustc_attr_ir::{Attribute, AttributeKind, RustcShowSpansKind}; @@ -9,15 +11,20 @@ use crate::diagnostics; struct ShowSpans<'a> { sess: &'a Session, + kinds: ShowSpanKinds, +} + +#[derive(Clone, Copy, Default)] +struct ShowSpanKinds { expr: bool, ty: bool, path: bool, + generic_args: bool, } impl<'a> Visitor<'a> for ShowSpans<'a> { fn visit_item(&mut self, item: &'a ast::Item) { - let saved = (self.expr, self.ty, self.path); - (self.expr, self.ty, self.path) = (false, false, false); + let saved = mem::take(&mut self.kinds); if let ItemKind::Fn(_) = &item.kind && let Some(Attribute::Parsed(AttributeKind::RustcShowSpans(kinds))) = @@ -25,43 +32,53 @@ impl<'a> Visitor<'a> for ShowSpans<'a> { { for kind in kinds { match kind { - RustcShowSpansKind::Expr => self.expr = true, - RustcShowSpansKind::Ty => self.ty = true, - RustcShowSpansKind::Path => self.path = true, + RustcShowSpansKind::Expr => self.kinds.expr = true, + RustcShowSpansKind::Ty => self.kinds.ty = true, + RustcShowSpansKind::Path => self.kinds.path = true, + RustcShowSpansKind::GenericArgs => self.kinds.generic_args = true, } } } visit::walk_item(self, item); // Recover the state. Needed if we are looking into nested items. - (self.expr, self.ty, self.path) = saved; + self.kinds = saved; } // We override it as to not report attribute paths as paths. fn visit_attribute(&mut self, _: &'a ast::Attribute) {} fn visit_expr(&mut self, e: &'a ast::Expr) { - if self.expr { + if self.kinds.expr { self.sess.dcx().emit_note(diagnostics::ShowSpan { span: e.span, kind: "expr" }); } visit::walk_expr(self, e); } fn visit_ty(&mut self, t: &'a ast::Ty) { - if self.ty { + if self.kinds.ty { self.sess.dcx().emit_note(diagnostics::ShowSpan { span: t.span, kind: "ty" }); } visit::walk_ty(self, t); } fn visit_path(&mut self, p: &'a ast::Path) { - if self.path { + if self.kinds.path { self.sess.dcx().emit_note(diagnostics::ShowSpan { span: p.span, kind: "path" }); } visit::walk_path(self, p); } + + fn visit_generic_args(&mut self, g: &'a ast::GenericArgs) { + if self.kinds.generic_args { + self.sess + .dcx() + .emit_note(diagnostics::ShowSpan { span: g.span(), kind: "generic_args" }); + } + visit::walk_generic_args(self, g); + } } pub fn check_crate(sess: &Session, krate: &ast::Crate) { - visit::walk_crate(&mut ShowSpans { sess, expr: false, ty: false, path: false }, krate); + visit::walk_crate(&mut ShowSpans { sess, kinds: ShowSpanKinds::default() }, krate); } diff --git a/compiler/rustc_attr_ir/src/data_structures.rs b/compiler/rustc_attr_ir/src/data_structures.rs index 6e86fd3f3aa5c..323a66f96ec3f 100644 --- a/compiler/rustc_attr_ir/src/data_structures.rs +++ b/compiler/rustc_attr_ir/src/data_structures.rs @@ -612,6 +612,7 @@ pub enum RustcShowSpansKind { Expr, Ty, Path, + GenericArgs, } #[derive(Clone, Debug, StableHash, Encodable, Decodable, PrintAttribute)] @@ -1365,8 +1366,10 @@ pub enum AttributeKind { /// Represents `#[rustc_insignificant_dtor]` RustcInsignificantDtor, - /// Represents `#[rustc_intrinsic]` - RustcIntrinsic, + /// Represents `#[rustc_intrinsic]` / `#[rustc_intrinsic(llvm = "...")]` + RustcIntrinsic { + llvm: Option, + }, /// Represents `#[rustc_intrinsic_const_stable_indirect]` RustcIntrinsicConstStableIndirect, diff --git a/compiler/rustc_attr_ir/src/encode_cross_crate.rs b/compiler/rustc_attr_ir/src/encode_cross_crate.rs index 0f4bb8f167d9f..73c7c5598f36a 100644 --- a/compiler/rustc_attr_ir/src/encode_cross_crate.rs +++ b/compiler/rustc_attr_ir/src/encode_cross_crate.rs @@ -157,7 +157,7 @@ impl AttributeKind { RustcIfThisChanged(..) => No, RustcInheritOverflowChecks => No, RustcInsignificantDtor => Yes, - RustcIntrinsic => Yes, + RustcIntrinsic { .. } => Yes, RustcIntrinsicConstStableIndirect => No, RustcLegacyConstGenerics { .. } => Yes, RustcLintOptDenyFieldAccess { .. } => Yes, @@ -376,7 +376,7 @@ impl AttributeKind { RustcIfThisChanged(..) => false, RustcInheritOverflowChecks => false, RustcInsignificantDtor => false, - RustcIntrinsic => false, + RustcIntrinsic { .. } => false, RustcIntrinsicConstStableIndirect => false, RustcLegacyConstGenerics { .. } => false, RustcLintOptDenyFieldAccess { .. } => false, diff --git a/compiler/rustc_attr_parsing/src/attributes/cfg.rs b/compiler/rustc_attr_parsing/src/attributes/cfg.rs index d904e120eb349..8846ed766e7f3 100644 --- a/compiler/rustc_attr_parsing/src/attributes/cfg.rs +++ b/compiler/rustc_attr_parsing/src/attributes/cfg.rs @@ -395,7 +395,7 @@ fn parse_cfg_attr_internal<'a>( attribute.span, item.span, attribute.style, - AttrPath { segments: attribute.path().into_boxed_slice(), span: attribute.span }, + AttrPath::from_ast(&item.path, identity), Some(item.unsafety), AttributeSafety::Normal, ParsedDescription::Attribute, diff --git a/compiler/rustc_attr_parsing/src/attributes/doc.rs b/compiler/rustc_attr_parsing/src/attributes/doc.rs index aebde3867ebd2..c8090ffcd1e9f 100644 --- a/compiler/rustc_attr_parsing/src/attributes/doc.rs +++ b/compiler/rustc_attr_parsing/src/attributes/doc.rs @@ -10,12 +10,13 @@ use rustc_feature::AttributeStability; use rustc_lint_defs::builtin::{INVALID_DOC_ATTRIBUTES, UNUSED_ATTRIBUTES}; use rustc_span::{Span, Symbol, edition, kw, sym}; -use super::prelude::{ALL_TARGETS, AllowedTargets}; +use super::prelude::AllowedTargets; use super::{AcceptMapping, AttributeParser, template}; +use crate::attributes::doc_comment::DOC_TARGETS; use crate::context::{AcceptContext, FinalizeContext}; use crate::diagnostics::{ DocAliasBadChar, DocAliasDuplicated, DocAliasEmpty, DocAliasMalformed, DocAliasStartEnd, - DocAttrNotCrateLevel, DocAttrNotParameters, DocAttrNotTraitLevel, DocAttributeNotAttribute, + DocAttrNotCrateLevel, DocAttrNotTraitLevel, DocAttributeNotAttribute, DocAutoCfgExpectsHideOrShow, DocAutoCfgHideShowExpectsList, DocAutoCfgHideShowNoIdentBeforeValues, DocAutoCfgHideShowUnexpectedItem, DocAutoCfgHideShowUnexpectedItemAfterValues, DocAutoCfgHideShowValuesMix, @@ -864,9 +865,6 @@ impl DocParser { } fn accept_single_doc_attr(&mut self, cx: &mut AcceptContext<'_, '_>, args: &ArgParser) { - if cx.shared.target == Target::Param { - cx.emit_err(DocAttrNotParameters { span: cx.attr_span }); - } match args { ArgParser::List(items) if !items.is_empty() => { for i in items.mixed() { @@ -934,43 +932,7 @@ impl AttributeParser for DocParser { this.accept_single_doc_attr(cx, args); }, )]; - // FIXME: Currently emitted from 2 different places, generating duplicated warnings. - const ALLOWED_TARGETS: AllowedTargets<'_> = AllowedTargets::AllowList(ALL_TARGETS); - // const ALLOWED_TARGETS: AllowedTargets<'_> = AllowedTargets::AllowListWarnRest(&[ - // Allow(Target::ExternCrate), - // Allow(Target::Use), - // Allow(Target::Static), - // Allow(Target::Const), - // Allow(Target::Fn), - // Allow(Target::Mod), - // Allow(Target::ForeignMod), - // Allow(Target::TyAlias), - // Allow(Target::Enum), - // Allow(Target::Variant), - // Allow(Target::Struct), - // Allow(Target::Field), - // Allow(Target::Union), - // Allow(Target::Trait), - // Allow(Target::TraitAlias), - // Allow(Target::Impl { of_trait: true }), - // Allow(Target::Impl { of_trait: false }), - // Allow(Target::AssocConst(AssocCtxt::Impl { of_trait: false })), - // Allow(Target::AssocConst(AssocCtxt::Trait)), - // Allow(Target::AssocConst(AssocCtxt::Impl { of_trait: true })), - // Allow(Target::Method(MethodKind::Inherent)), - // Allow(Target::Method(MethodKind::Trait { body: true })), - // Allow(Target::Method(MethodKind::Trait { body: false })), - // Allow(Target::Method(MethodKind::TraitImpl)), - // Allow(Target::AssocTy(AssocCtxt::Impl { of_trait: false })), - // Allow(Target::AssocTy(AssocCtxt::Trait)), - // Allow(Target::AssocTy(AssocCtxt::Impl { of_trait: true })), - // Allow(Target::ForeignFn), - // Allow(Target::ForeignStatic), - // Allow(Target::ForeignTy), - // Allow(Target::MacroDef), - // Allow(Target::Crate), - // Error(Target::WherePredicate), - // ]); + const ALLOWED_TARGETS: AllowedTargets<'_> = DOC_TARGETS; fn finalize(self, _cx: &FinalizeContext<'_, '_>) -> Option { if self.nb_doc_attrs != 0 { diff --git a/compiler/rustc_attr_parsing/src/attributes/doc_comment.rs b/compiler/rustc_attr_parsing/src/attributes/doc_comment.rs new file mode 100644 index 0000000000000..932be836f0661 --- /dev/null +++ b/compiler/rustc_attr_parsing/src/attributes/doc_comment.rs @@ -0,0 +1,97 @@ +use std::mem; + +use rustc_ast::AttrKind; +use rustc_ast::token::CommentKind; +use rustc_ast::visit::AssocCtxt; +use rustc_attr_ir::target::{AstTarget, MethodKind, Target}; +use rustc_errors::{Diagnostic, MultiSpan}; +use rustc_lint_defs::LintId; +use rustc_lint_defs::builtin::UNUSED_DOC_COMMENTS; +use rustc_span::Span; + +use crate::attributes::prelude::{Allow, Error}; +use crate::diagnostics::{BuiltinUnusedDocComment, BuiltinUnusedDocCommentSub}; +use crate::target_checking::Policy::AllowSilent; +use crate::target_checking::{AllowedResult, AllowedTargets}; +use crate::{AttributeParser, EmitAttribute, ShouldEmit}; + +pub(crate) fn target_check_doc_comment( + parser: &AttributeParser<'_>, + attr: &rustc_ast::Attribute, + target: &AstTarget<'_>, + target_span: Span, + emit_lint: &mut impl FnMut(LintId, MultiSpan, EmitAttribute), + has_target_checked_doc_comment: &mut bool, +) { + if matches!(parser.should_emit, ShouldEmit::Nothing) { + return; + } + if mem::replace(has_target_checked_doc_comment, true) { + return; + } + let target = Target::from_ast_target(target); + let res = DOC_TARGETS.is_allowed(target); + if res == AllowedResult::Allowed { + return; + } + + let sub = match attr.kind { + AttrKind::DocComment(CommentKind::Line, _) | AttrKind::Normal(..) => { + BuiltinUnusedDocCommentSub::PlainHelp + } + AttrKind::DocComment(CommentKind::Block, _) => BuiltinUnusedDocCommentSub::BlockHelp, + AttrKind::Synthetic(..) | AttrKind::Generated(..) => unreachable!(), + }; + + let context = + if attr.span.ctxt() == target_span.ctxt() { target_span.shrink_to_lo() } else { attr.span }; + + let attr_span = attr.span; + emit_lint( + LintId::of(UNUSED_DOC_COMMENTS), + attr_span.into(), + EmitAttribute(Box::new(move |dcx, level, _| { + BuiltinUnusedDocComment { sub, target: target.plural_name(), label: attr_span, context } + .into_diag(dcx, level) + })), + ); +} + +/// This set of targets is used both for the `doc` attribute and doc comments. +pub(crate) const DOC_TARGETS: AllowedTargets<'static> = { + AllowedTargets::AllowListWarnRest(&[ + Allow(Target::Use), + Allow(Target::Static), + Allow(Target::Const), + Allow(Target::Fn), + Allow(Target::Mod), + Allow(Target::Enum), + Allow(Target::Variant), + Allow(Target::Struct), + Allow(Target::Field), + Allow(Target::Union), + Allow(Target::Trait), + Allow(Target::TraitAlias), + Allow(Target::TyAlias), + Allow(Target::AssocConst(AssocCtxt::Impl { of_trait: false })), + Allow(Target::AssocConst(AssocCtxt::Trait)), + Allow(Target::AssocConst(AssocCtxt::Impl { of_trait: true })), + Allow(Target::Method(MethodKind::Inherent)), + Allow(Target::Method(MethodKind::Trait { body: false })), + Allow(Target::Method(MethodKind::Trait { body: true })), + Allow(Target::Method(MethodKind::TraitImpl)), + Allow(Target::AssocTy(AssocCtxt::Impl { of_trait: false })), + Allow(Target::AssocTy(AssocCtxt::Trait)), + Allow(Target::AssocTy(AssocCtxt::Impl { of_trait: true })), + Allow(Target::ForeignFn), + Allow(Target::ForeignStatic), + Allow(Target::ForeignTy), + Allow(Target::MacroDef), + Allow(Target::Crate), + Allow(Target::ExternCrate), + Allow(Target::Impl { of_trait: false }), + Allow(Target::Impl { of_trait: true }), + AllowSilent(Target::WherePredicate), // Error, checked elsewhere + Error(Target::Param), + ]) +}; diff --git a/compiler/rustc_attr_parsing/src/attributes/mod.rs b/compiler/rustc_attr_parsing/src/attributes/mod.rs index 1a9c23150a894..7475c86ba14d0 100644 --- a/compiler/rustc_attr_parsing/src/attributes/mod.rs +++ b/compiler/rustc_attr_parsing/src/attributes/mod.rs @@ -48,6 +48,7 @@ pub(crate) mod debugger; pub(crate) mod deprecation; pub(crate) mod diagnostic; pub(crate) mod doc; +pub(crate) mod doc_comment; pub(crate) mod dummy; pub(crate) mod inline; pub(crate) mod instruction_set; diff --git a/compiler/rustc_attr_parsing/src/attributes/prelude.rs b/compiler/rustc_attr_parsing/src/attributes/prelude.rs index 76ce02833d797..d406cfb6c2b0b 100644 --- a/compiler/rustc_attr_parsing/src/attributes/prelude.rs +++ b/compiler/rustc_attr_parsing/src/attributes/prelude.rs @@ -18,11 +18,11 @@ pub(super) use crate::attributes::{ pub(super) use crate::context::{AcceptContext, FinalizeCheckContext, FinalizeContext}; #[doc(hidden)] pub(super) use crate::parser::*; +#[doc(hidden)] +pub(super) use crate::target_checking::AllowedTargets; // target checking #[doc(hidden)] pub(super) use crate::target_checking::Policy::{Allow, Error, Warn}; #[doc(hidden)] -pub(super) use crate::target_checking::{ALL_TARGETS, AllowedTargets}; -#[doc(hidden)] pub(super) use crate::unstable; pub(super) use crate::{AttributeTemplate, template}; diff --git a/compiler/rustc_attr_parsing/src/attributes/rustc_dump.rs b/compiler/rustc_attr_parsing/src/attributes/rustc_dump.rs index 07ce47b8858e2..9a2a9681f78ea 100644 --- a/compiler/rustc_attr_parsing/src/attributes/rustc_dump.rs +++ b/compiler/rustc_attr_parsing/src/attributes/rustc_dump.rs @@ -331,9 +331,12 @@ impl SingleAttributeParser for RustcShowSpans { sym::expr => RustcShowSpansKind::Expr, sym::ty => RustcShowSpansKind::Ty, sym::path => RustcShowSpansKind::Path, + sym::generic_args => RustcShowSpansKind::GenericArgs, _ => { - cx.adcx() - .expected_specific_argument(ident.span, &[sym::expr, sym::ty, sym::path]); + cx.adcx().expected_specific_argument( + ident.span, + &[sym::expr, sym::ty, sym::path, sym::generic_args], + ); continue; } }; diff --git a/compiler/rustc_attr_parsing/src/attributes/rustc_internal.rs b/compiler/rustc_attr_parsing/src/attributes/rustc_internal.rs index 0c056240a81d4..cf1209f717d22 100644 --- a/compiler/rustc_attr_parsing/src/attributes/rustc_internal.rs +++ b/compiler/rustc_attr_parsing/src/attributes/rustc_internal.rs @@ -1113,11 +1113,28 @@ impl SingleAttributeParser for RustcDocPrimitiveParser { pub(crate) struct RustcIntrinsicParser; -impl NoArgsAttributeParser for RustcIntrinsicParser { +impl SingleAttributeParser for RustcIntrinsicParser { const PATH: &[Symbol] = &[sym::rustc_intrinsic]; const ALLOWED_TARGETS: AllowedTargets<'_> = AllowedTargets::AllowList(&[Allow(Target::Fn)]); + const TEMPLATE: AttributeTemplate = template!(Word, List: &[r#"llvm = "...""#]); const STABILITY: AttributeStability = unstable!(intrinsics); - const CREATE: fn(Span) -> AttributeKind = |_| AttributeKind::RustcIntrinsic; + + fn convert(cx: &mut AcceptContext<'_, '_>, args: &ArgParser) -> Option { + match args { + ArgParser::NoArgs => Some(AttributeKind::RustcIntrinsic { llvm: None }), + ArgParser::List(_) => { + let item = cx.expect_single_element_list(args, cx.attr_span)?; + let nv = cx.expect_name_value(item, item.span(), Some(sym::llvm))?; + let name = cx.expect_string_literal(nv.1)?; + Some(AttributeKind::RustcIntrinsic { llvm: Some(name) }) + } + ArgParser::NameValue(_) => { + let span = cx.attr_span; + cx.adcx().expected_list_or_no_args(span); + None + } + } + } } pub(crate) struct RustcIntrinsicConstStableIndirectParser; diff --git a/compiler/rustc_attr_parsing/src/context.rs b/compiler/rustc_attr_parsing/src/context.rs index 547649313ac44..cb70e10b2d92f 100644 --- a/compiler/rustc_attr_parsing/src/context.rs +++ b/compiler/rustc_attr_parsing/src/context.rs @@ -244,6 +244,7 @@ attribute_parsers!( Single, Single, Single, + Single, Single, Single, Single, @@ -332,7 +333,6 @@ attribute_parsers!( Single>, Single>, Single>, - Single>, Single>, Single>, Single>, diff --git a/compiler/rustc_attr_parsing/src/diagnostics.rs b/compiler/rustc_attr_parsing/src/diagnostics.rs index d419bcd429a3b..868f4b347a27f 100644 --- a/compiler/rustc_attr_parsing/src/diagnostics.rs +++ b/compiler/rustc_attr_parsing/src/diagnostics.rs @@ -1060,13 +1060,6 @@ pub(crate) struct DocAttrNotCrateLevel { pub attr_name: Symbol, } -#[derive(Diagnostic)] -#[diag("`#[doc(...)]` isn't allowed on parameters")] -pub(crate) struct DocAttrNotParameters { - #[primary_span] - pub span: Span, -} - #[derive(Diagnostic)] #[diag("nonexistent keyword `{$keyword}` used in `#[doc(keyword = \"...\")]`")] #[help("only existing keywords are allowed in core/std")] @@ -2271,3 +2264,23 @@ pub(crate) struct UnknownLintHelper { pub span: Span, pub unknown: Symbol, } + +#[derive(Diagnostic)] +#[diag("unused doc comment")] +pub(crate) struct BuiltinUnusedDocComment { + #[subdiagnostic] + pub sub: BuiltinUnusedDocCommentSub, + pub target: &'static str, + #[label("rustdoc does not generate documentation for {$target}")] + pub label: Span, + #[context] + pub context: Span, +} + +#[derive(Subdiagnostic)] +pub(crate) enum BuiltinUnusedDocCommentSub { + #[help("use `//` for a plain comment")] + PlainHelp, + #[help("use `/* */` for a plain comment")] + BlockHelp, +} diff --git a/compiler/rustc_attr_parsing/src/interface.rs b/compiler/rustc_attr_parsing/src/interface.rs index 9bd489a5aea8f..92cf6813bd22e 100644 --- a/compiler/rustc_attr_parsing/src/interface.rs +++ b/compiler/rustc_attr_parsing/src/interface.rs @@ -15,6 +15,7 @@ use rustc_session::Session; use rustc_span::{DUMMY_SP, ErrorGuaranteed, Span, Symbol, sym}; use crate::attributes::AttributeSafety; +use crate::attributes::doc_comment::target_check_doc_comment; use crate::context::{ ATTRIBUTE_PARSERS, AcceptContext, FinalizeCheckContext, FinalizeCheckFn, FinalizeContext, FinalizeFn, FinalizeOutput, SharedContext, @@ -326,6 +327,7 @@ impl<'sess> AttributeParser<'sess> { let mut attr_paths: Vec> = Vec::new(); let mut synthetic_attr_state = SyntheticAttrState::default(); let mut generated_attr_state = GeneratedAttrState::default(); + let mut has_target_checked_doc_comment = false; let mut finalizers: Vec = Vec::with_capacity(attrs.len()); @@ -340,6 +342,14 @@ impl<'sess> AttributeParser<'sess> { let attr_span = lower_span(attr.span); match &attr.kind { ast::AttrKind::DocComment(comment_kind, symbol) => { + target_check_doc_comment( + &self, + attr, + &ast_target, + target_span, + &mut emit_lint, + &mut has_target_checked_doc_comment, + ); attributes.push(Attribute::Parsed(AttributeKind::DocComment { style: attr.style, kind: DocFragmentKind::Sugared(*comment_kind), @@ -406,6 +416,14 @@ impl<'sess> AttributeParser<'sess> { // emit an error with `AcceptContext`. && let Some(comment) = nv.value_as_str() { + target_check_doc_comment( + &self, + attr, + &ast_target, + target_span, + &mut emit_lint, + &mut false, // always linted + ); attributes.push(Attribute::Parsed(AttributeKind::DocComment { style: attr.style, kind: DocFragmentKind::Raw(nv.value_span), diff --git a/compiler/rustc_attr_parsing/src/target_checking.rs b/compiler/rustc_attr_parsing/src/target_checking.rs index 0dfd7aa0b8acf..887b269881cee 100644 --- a/compiler/rustc_attr_parsing/src/target_checking.rs +++ b/compiler/rustc_attr_parsing/src/target_checking.rs @@ -1,12 +1,13 @@ use std::borrow::Cow; use rustc_ast::{AttrStyle, Safety}; -use rustc_attr_ir::target::{AssocCtxt, MethodKind, Target}; +use rustc_attr_ir::target::{MethodKind, Target}; use rustc_attr_ir::{AttrItem, Attribute, AttributeKind}; use rustc_errors::{DiagArgValue, MultiSpan, StashKey}; use rustc_feature::Features; use rustc_lint_defs::builtin::{ - INVALID_DOC_ATTRIBUTES, MISPLACED_DIAGNOSTIC_ATTRIBUTES, UNUSED_ATTRIBUTES, USELESS_DEPRECATED, + INVALID_DOC_ATTRIBUTES, MISPLACED_DIAGNOSTIC_ATTRIBUTES, UNUSED_ATTRIBUTES, + UNUSED_DOC_COMMENTS, USELESS_DEPRECATED, }; use rustc_span::{BytePos, FileName, RemapPathScopeComponents, Span, Symbol, sym}; @@ -28,6 +29,7 @@ pub(crate) enum AllowedTargets<'a> { ManuallyChecked, } +#[derive(Eq, PartialEq, Copy, Clone)] pub(crate) enum AllowedResult { Allowed, Warn, @@ -181,6 +183,8 @@ impl<'sess> AttributeParser<'sess> { .contains(&cx.target) { USELESS_DEPRECATED + } else if cx.attr_path.segments[0] == sym::doc && attribute_args == "" { + UNUSED_DOC_COMMENTS //FIXME this is strange... } else if is_diagnostic_attr { MISPLACED_DIAGNOSTIC_ATTRIBUTES } else { @@ -506,64 +510,3 @@ impl<'f, 'sess> AcceptContext<'f, 'sess> { } } } - -/// This is the list of all targets to which a attribute can be applied -/// This is used for: -/// - `rustc_dummy`, which can be applied to all targets -/// - Attributes that are not parted to the new target system yet can use this list as a placeholder -pub(crate) const ALL_TARGETS: &[Policy] = { - use Policy::Allow; - &[ - Allow(Target::ExternCrate), - Allow(Target::Use), - Allow(Target::Static), - Allow(Target::Const), - Allow(Target::Fn), - Allow(Target::Closure), - Allow(Target::Mod), - Allow(Target::ForeignMod), - Allow(Target::GlobalAsm), - Allow(Target::TyAlias), - Allow(Target::Enum), - Allow(Target::Variant), - Allow(Target::Struct), - Allow(Target::Field), - Allow(Target::Union), - Allow(Target::Trait), - Allow(Target::TraitAlias), - Allow(Target::Impl { of_trait: false }), - Allow(Target::Impl { of_trait: true }), - Allow(Target::Expression), - Allow(Target::Statement), - Allow(Target::Arm), - Allow(Target::AssocConst(AssocCtxt::Impl { of_trait: false })), - Allow(Target::AssocConst(AssocCtxt::Trait)), - Allow(Target::AssocConst(AssocCtxt::Impl { of_trait: true })), - Allow(Target::Method(MethodKind::Inherent)), - Allow(Target::Method(MethodKind::Trait { body: false })), - Allow(Target::Method(MethodKind::Trait { body: true })), - Allow(Target::Method(MethodKind::TraitImpl)), - Allow(Target::AssocTy(AssocCtxt::Impl { of_trait: false })), - Allow(Target::AssocTy(AssocCtxt::Trait)), - Allow(Target::AssocTy(AssocCtxt::Impl { of_trait: true })), - Allow(Target::ForeignFn), - Allow(Target::ForeignStatic), - Allow(Target::ForeignTy), - Allow(Target::MacroDef), - Allow(Target::Param), - Allow(Target::PatField), - Allow(Target::ExprField), - Allow(Target::WherePredicate), - Allow(Target::MacroCall), - Allow(Target::Crate), - Allow(Target::Delegation { mac: false }), - Allow(Target::Delegation { mac: true }), - Allow(Target::ConstParam), - Allow(Target::LifetimeParam), - Allow(Target::TypeParam), - Allow(Target::Loop), - Allow(Target::ForLoop), - Allow(Target::While), - Allow(Target::Break), - ] -}; diff --git a/compiler/rustc_borrowck/src/type_check/mod.rs b/compiler/rustc_borrowck/src/type_check/mod.rs index d745bb68ff757..97b0c0f12fc10 100644 --- a/compiler/rustc_borrowck/src/type_check/mod.rs +++ b/compiler/rustc_borrowck/src/type_check/mod.rs @@ -25,8 +25,8 @@ use rustc_middle::traits::query::NoSolution; use rustc_middle::ty::adjustment::PointerCoercion; use rustc_middle::ty::cast::CastTy; use rustc_middle::ty::{ - self, CanonicalUserTypeAnnotation, CanonicalUserTypeAnnotations, GenericArgs, Ty, TyCtxt, - TypeVisitableExt, UserArgs, UserTypeAnnotationIndex, fold_regions, + self, CanonicalUserTypeAnnotation, CanonicalUserTypeAnnotations, GenericArgs, Intrinsic, Ty, + TyCtxt, TypeVisitableExt, UserArgs, UserTypeAnnotationIndex, fold_regions, }; use rustc_mir_dataflow::move_paths::MoveData; use rustc_mir_dataflow::points::DenseLocationMap; @@ -2032,8 +2032,9 @@ impl<'a, 'tcx> TypeChecker<'a, 'tcx> { // Some of the SIMD intrinsics are special: they need a particular argument to be a // constant. (Eventually this should use const-generics, but those are not up for the // task yet: https://github.com/rust-lang/rust/issues/85229.) - if let Some(name @ (sym::simd_shuffle | sym::simd_insert | sym::simd_extract)) = - self.tcx().intrinsic(def_id).map(|i| i.name) + if let Some(Intrinsic::Rustc( + name @ (sym::simd_shuffle | sym::simd_insert | sym::simd_extract), + )) = self.tcx().intrinsic(def_id).map(|i| i.name) { let idx = match name { sym::simd_shuffle => 2, diff --git a/compiler/rustc_builtin_macros/src/deriving/default.rs b/compiler/rustc_builtin_macros/src/deriving/default.rs index efefcf0006387..6aa45b9d41126 100644 --- a/compiler/rustc_builtin_macros/src/deriving/default.rs +++ b/compiler/rustc_builtin_macros/src/deriving/default.rs @@ -293,7 +293,7 @@ fn validate_default_attribute( return Err(guar); } }; - if !attr.is_word() { + if !attr.get_normal_item().is_word() { let guar = cx.dcx().emit_err(diagnostics::DefaultHasArg { span: attr.span }); return Err(guar); diff --git a/compiler/rustc_codegen_cranelift/src/intrinsics/mod.rs b/compiler/rustc_codegen_cranelift/src/intrinsics/mod.rs index e5cbca01aa051..d2e5a4e6661e2 100644 --- a/compiler/rustc_codegen_cranelift/src/intrinsics/mod.rs +++ b/compiler/rustc_codegen_cranelift/src/intrinsics/mod.rs @@ -20,10 +20,9 @@ mod simd; use cranelift_codegen::ir::{ AtomicRmwOp, BlockArg, ExceptionTableData, ExceptionTableItem, ExceptionTag, }; -use rustc_middle::ty; -use rustc_middle::ty::GenericArgs; use rustc_middle::ty::layout::{HasTypingEnv as _, ValidityRequirement}; use rustc_middle::ty::print::{with_no_trimmed_paths, with_no_visible_paths}; +use rustc_middle::ty::{self, GenericArgs, Intrinsic, IntrinsicDef}; use rustc_span::{Spanned, Symbol, sym}; use rustc_target::spec::PanicStrategy; @@ -284,9 +283,14 @@ pub(crate) fn codegen_intrinsic_call<'tcx>( return Err(Instance::new_raw(instance.def_id(), instance.args)); } - let intrinsic = fx.tcx.item_name(instance.def_id()); + let intrinsic = fx.tcx.intrinsic(instance.def_id()).unwrap(); let instance_args = instance.args; + let Intrinsic::Rustc(intrinsic) = intrinsic.name else { + // Backend intrinsics use their fallback bodies for now. + return intrinsic_fallback(instance, intrinsic, source_info); + }; + if intrinsic.as_str().starts_with("simd_") { self::simd::codegen_simd_intrinsic_call( fx, @@ -591,7 +595,7 @@ fn codegen_regular_intrinsic_call<'tcx>( let ty = generic_args.type_at(0); - let requirement = ValidityRequirement::from_intrinsic(intrinsic); + let requirement = ValidityRequirement::from_rustc_intrinsic(intrinsic); if let Some(requirement) = requirement { let do_panic = !fx @@ -1450,14 +1454,7 @@ fn codegen_regular_intrinsic_call<'tcx>( // by converting the `InstanceKind::Intrinsic` to an `InstanceKind::Item`. _ => { let intrinsic = fx.tcx.intrinsic(instance.def_id()).unwrap(); - if intrinsic.must_be_overridden { - span_bug!( - source_info.span, - "intrinsic {} must be overridden by codegen_cranelift, but isn't", - intrinsic.name, - ); - } - return Err(Instance::new_raw(instance.def_id(), instance.args)); + return intrinsic_fallback(instance, intrinsic, source_info); } } @@ -1465,3 +1462,18 @@ fn codegen_regular_intrinsic_call<'tcx>( fx.bcx.ins().jump(ret_block, &[]); Ok(()) } + +fn intrinsic_fallback<'tcx>( + instance: Instance<'tcx>, + intrinsic: IntrinsicDef, + source_info: mir::SourceInfo, +) -> Result<(), Instance<'tcx>> { + if intrinsic.must_be_overridden { + span_bug!( + source_info.span, + "intrinsic {} must be overridden by codegen_cranelift, but isn't", + intrinsic.name, + ); + } + return Err(Instance::new_raw(instance.def_id(), instance.args)); +} diff --git a/compiler/rustc_codegen_cranelift/src/lib.rs b/compiler/rustc_codegen_cranelift/src/lib.rs index a30dd1c3ebef3..1ff093f9cc556 100644 --- a/compiler/rustc_codegen_cranelift/src/lib.rs +++ b/compiler/rustc_codegen_cranelift/src/lib.rs @@ -155,8 +155,8 @@ impl CodegenBackend for CraneliftCodegenBackend { CodegenBackendInit { global_backend_features: vec![], - replaced_intrinsics: vec![], - fallback_intrinsics: vec![sym::type_id_eq], + replaced_rustc_intrinsics: vec![], + fallback_rustc_intrinsics: vec![sym::type_id_eq], thin_lto_supported: false, } } diff --git a/compiler/rustc_codegen_gcc/src/context.rs b/compiler/rustc_codegen_gcc/src/context.rs index f4461a268c2d5..2811057bab1bd 100644 --- a/compiler/rustc_codegen_gcc/src/context.rs +++ b/compiler/rustc_codegen_gcc/src/context.rs @@ -16,11 +16,11 @@ use rustc_middle::ty::layout::{ FnAbiError, FnAbiOf, FnAbiOfHelpers, FnAbiRequest, HasTyCtxt, HasTypingEnv, LayoutError, LayoutOfHelpers, codegen_handle_fn_abi_err, }; -use rustc_middle::ty::{self, ExistentialTraitRef, Instance, Ty, TyCtxt}; +use rustc_middle::ty::{self, ExistentialTraitRef, Instance, Intrinsic, Ty, TyCtxt}; #[cfg(feature = "master")] use rustc_session::config::DebugInfo; use rustc_session::{PointerAuthSchema, Session}; -use rustc_span::{DUMMY_SP, Span, Symbol}; +use rustc_span::{DUMMY_SP, Span}; use rustc_target::spec::{HasTargetSpec, HasX86AbiOpt, Target, TlsModel, X86Abi}; #[cfg(feature = "master")] @@ -560,7 +560,7 @@ impl<'gcc, 'tcx> MiscCodegenMethods<'tcx> for CodegenCx<'gcc, 'tcx> { } } - fn intrinsic_call_expects_place_always(&self, _name: Symbol) -> bool { + fn intrinsic_call_expects_place_always(&self, _name: Intrinsic) -> bool { true } } diff --git a/compiler/rustc_codegen_gcc/src/intrinsic/mod.rs b/compiler/rustc_codegen_gcc/src/intrinsic/mod.rs index ca98ae6319b7f..350fb01df53c8 100644 --- a/compiler/rustc_codegen_gcc/src/intrinsic/mod.rs +++ b/compiler/rustc_codegen_gcc/src/intrinsic/mod.rs @@ -23,7 +23,7 @@ use rustc_data_structures::fx::FxHashSet; #[cfg(feature = "master")] use rustc_middle::ty::layout::FnAbiOf; use rustc_middle::ty::layout::LayoutOf; -use rustc_middle::ty::{self, Instance, Ty}; +use rustc_middle::ty::{self, Instance, Intrinsic, Ty}; use rustc_session::config::OptLevel; use rustc_span::{Span, Symbol, bug, span_bug, sym}; use rustc_target::callconv::{ArgAbi, PassMode}; @@ -133,7 +133,12 @@ impl<'a, 'gcc, 'tcx> IntrinsicCallBuilderMethods<'tcx> for Builder<'a, 'gcc, 'tc let result = PlaceRef { val: result_place.unwrap(), layout: result_layout }; - let name = tcx.item_name(instance.def_id()); + let intrinsic = tcx.intrinsic(instance.def_id()).unwrap(); + let Intrinsic::Rustc(name) = intrinsic.name else { + // Backend intrinsics use their fallback bodies for now. + let fallback = Instance::new_raw(instance.def_id(), instance.args); + return IntrinsicResult::Fallback(fallback); + }; let name_str = name.as_str(); let fn_args = instance.args; @@ -242,7 +247,7 @@ impl<'a, 'gcc, 'tcx> IntrinsicCallBuilderMethods<'tcx> for Builder<'a, 'gcc, 'tc None => { let err = tcx.dcx().emit_err(InvalidMonomorphization::BasicIntegerType { span, - name, + name: Intrinsic::Rustc(name), ty: args[0].layout.ty, }); return IntrinsicResult::Err(err); diff --git a/compiler/rustc_codegen_gcc/src/intrinsic/simd.rs b/compiler/rustc_codegen_gcc/src/intrinsic/simd.rs index 6d3b447e66d1c..971f2f43cd8d2 100644 --- a/compiler/rustc_codegen_gcc/src/intrinsic/simd.rs +++ b/compiler/rustc_codegen_gcc/src/intrinsic/simd.rs @@ -16,7 +16,7 @@ use rustc_codegen_ssa::traits::{BaseTypeCodegenMethods, BuilderMethods}; use rustc_hir as hir; use rustc_middle::mir::BinOp; use rustc_middle::ty::layout::{HasTyCtxt, HasTypingEnv as _, LayoutOf}; -use rustc_middle::ty::{self, Ty}; +use rustc_middle::ty::{self, Intrinsic, Ty}; use rustc_span::{ErrorGuaranteed, Span, Symbol, span_bug, sym}; use crate::builder::Builder; @@ -864,7 +864,11 @@ pub fn generic_simd_intrinsic<'a, 'gcc, 'tcx>( }}; } let ty::Float(ref f) = *in_elem.kind() else { - return_error!(InvalidMonomorphization::BasicFloatType { span, name, ty: in_ty }); + return_error!(InvalidMonomorphization::BasicFloatType { + span, + name: Intrinsic::Rustc(name), + ty: in_ty + }); }; let elem_ty = bx.cx.type_float_from_ty(*f); let (elem_ty_str, elem_ty, cast_type) = match f.bit_width() { diff --git a/compiler/rustc_codegen_gcc/src/lib.rs b/compiler/rustc_codegen_gcc/src/lib.rs index fa15ec2838b24..896059c6897fb 100644 --- a/compiler/rustc_codegen_gcc/src/lib.rs +++ b/compiler/rustc_codegen_gcc/src/lib.rs @@ -290,8 +290,8 @@ impl CodegenBackend for GccCodegenBackend { CodegenBackendInit { global_backend_features, - replaced_intrinsics: vec![], - fallback_intrinsics: vec![sym::type_id_eq], + replaced_rustc_intrinsics: vec![], + fallback_rustc_intrinsics: vec![sym::type_id_eq], thin_lto_supported: false, } } diff --git a/compiler/rustc_codegen_llvm/src/back/llvm_backend.rs b/compiler/rustc_codegen_llvm/src/back/llvm_backend.rs index c0349b6003319..ee04b6770618f 100644 --- a/compiler/rustc_codegen_llvm/src/back/llvm_backend.rs +++ b/compiler/rustc_codegen_llvm/src/back/llvm_backend.rs @@ -288,8 +288,8 @@ impl CodegenBackend for LlvmCodegenBackend { CodegenBackendInit { global_backend_features, - replaced_intrinsics, - fallback_intrinsics, + replaced_rustc_intrinsics: replaced_intrinsics, + fallback_rustc_intrinsics: fallback_intrinsics, thin_lto_supported: true, } } diff --git a/compiler/rustc_codegen_llvm/src/consts.rs b/compiler/rustc_codegen_llvm/src/consts.rs index c8a934046cdbe..e9a1aae4d2140 100644 --- a/compiler/rustc_codegen_llvm/src/consts.rs +++ b/compiler/rustc_codegen_llvm/src/consts.rs @@ -699,7 +699,7 @@ impl<'ll> CodegenCx<'ll, '_> { let g = self.define_global(&sym, llty).unwrap_or_else(|| { bug!("symbol `{}` is already defined", sym); }); - set_global_alignment(self, g, self.tcx.data_layout.i8_align); + set_global_alignment(self, g, Align::ONE); llvm::set_initializer(g, llval); llvm::set_linkage(g, llvm::Linkage::PrivateLinkage); llvm::set_section(g, c"__TEXT,__cstring,cstring_literals"); @@ -812,7 +812,7 @@ impl<'ll> CodegenCx<'ll, '_> { let methname_g = self.define_global(&methname_sym, methname_llty).unwrap_or_else(|| { bug!("symbol `{}` is already defined", methname_sym); }); - set_global_alignment(self, methname_g, self.tcx.data_layout.i8_align); + set_global_alignment(self, methname_g, Align::ONE); llvm::set_initializer(methname_g, methname_llval); llvm::set_linkage(methname_g, llvm::Linkage::PrivateLinkage); llvm::set_section( diff --git a/compiler/rustc_codegen_llvm/src/context.rs b/compiler/rustc_codegen_llvm/src/context.rs index 999613db146a3..7151dcd32418d 100644 --- a/compiler/rustc_codegen_llvm/src/context.rs +++ b/compiler/rustc_codegen_llvm/src/context.rs @@ -18,7 +18,7 @@ use rustc_middle::ty::layout::{ FnAbiError, FnAbiOfHelpers, FnAbiRequest, HasTypingEnv, LayoutError, LayoutOfHelpers, codegen_handle_fn_abi_err, }; -use rustc_middle::ty::{self, Instance, Ty, TyCtxt}; +use rustc_middle::ty::{self, Instance, Intrinsic, Ty, TyCtxt}; use rustc_sanitizers::ignorelist::{SanitizerIgnoreList, typename_for_ignore_list}; use rustc_session::config::{ BranchProtection, CFGuard, CFProtection, DebugInfo, FunctionReturn, PAuthKey, PacRet, @@ -1100,8 +1100,8 @@ impl<'ll, 'tcx> MiscCodegenMethods<'tcx> for CodegenCx<'ll, 'tcx> { } } - fn intrinsic_call_expects_place_always(&self, name: Symbol) -> bool { - matches!(name, sym::black_box) + fn intrinsic_call_expects_place_always(&self, name: Intrinsic) -> bool { + matches!(name, Intrinsic::Rustc(sym::black_box)) } } diff --git a/compiler/rustc_codegen_llvm/src/intrinsic.rs b/compiler/rustc_codegen_llvm/src/intrinsic.rs index 0b442b3bdedeb..2f00202146f15 100644 --- a/compiler/rustc_codegen_llvm/src/intrinsic.rs +++ b/compiler/rustc_codegen_llvm/src/intrinsic.rs @@ -22,7 +22,7 @@ use rustc_middle::mir::interpret::{AllocId, Allocation, ErrorHandled, GlobalAllo use rustc_middle::mir::{self, BinOp}; use rustc_middle::ty::layout::{FnAbiOf, HasTyCtxt, HasTypingEnv, LayoutOf}; use rustc_middle::ty::offload_meta::OffloadMetadata; -use rustc_middle::ty::{self, GenericArgs, Instance, SimdAlign, Ty, TyCtxt}; +use rustc_middle::ty::{self, GenericArgs, Instance, Intrinsic, SimdAlign, Ty, TyCtxt}; use rustc_session::diagnostics::feature_err; use rustc_span::{ErrorGuaranteed, Span, Symbol, bug, span_bug, sym}; use rustc_structures::CrateType; @@ -84,19 +84,18 @@ impl<'ll, 'tcx> Builder<'_, 'll, 'tcx> { } } -impl<'ll, 'tcx> IntrinsicCallBuilderMethods<'tcx> for Builder<'_, 'll, 'tcx> { - fn codegen_intrinsic_call( +impl<'ll, 'tcx> Builder<'_, 'll, 'tcx> { + fn codegen_rustc_intrinsic_call( &mut self, instance: ty::Instance<'tcx>, args: &[OperandRef<'tcx, Value<'ll>>], result_layout: ty::layout::TyAndLayout<'tcx>, result_place: Option>>, span: Span, + name: Symbol, ) -> IntrinsicResult<'tcx, Value<'ll>> { let tcx = self.tcx; let llvm_version = crate::llvm_util::get_version(); - - let name = tcx.item_name(instance.def_id()); let fn_args = instance.args; let llval = match name { @@ -381,7 +380,7 @@ impl<'ll, 'tcx> IntrinsicCallBuilderMethods<'tcx> for Builder<'_, 'll, 'tcx> { if !ty.is_integral() { let err = tcx.dcx().emit_err(InvalidMonomorphization::BasicIntegerType { span, - name, + name: Intrinsic::Rustc(name), ty, }); return IntrinsicResult::Err(err); @@ -853,6 +852,15 @@ impl<'ll, 'tcx> IntrinsicCallBuilderMethods<'tcx> for Builder<'_, 'll, 'tcx> { } }; + self.llvm_value_to_intrinsicresult(llval, result_layout, result_place) + } + + fn llvm_value_to_intrinsicresult( + &mut self, + llval: Value<'ll>, + result_layout: ty::layout::TyAndLayout<'tcx>, + result_place: Option>>, + ) -> IntrinsicResult<'tcx, Value<'ll>> { if let BackendRepr::Memory { .. } = result_layout.backend_repr { // We have an llvm immediate, but that's not what cg_ssa expects, // so write it into the place (that always exists for memory) @@ -867,12 +875,12 @@ impl<'ll, 'tcx> IntrinsicCallBuilderMethods<'tcx> for Builder<'_, 'll, 'tcx> { } } - fn codegen_llvm_intrinsic_call( + fn codegen_llvm_intrinsic_call_impl( &mut self, instance: ty::Instance<'tcx>, - args: &[OperandRef<'tcx, Self::Value>], - _is_cleanup: bool, - ) -> Self::Value { + intrinsic_name: &str, + args: &[OperandRef<'tcx, Value<'ll>>], + ) -> Value<'ll> { let tcx = self.tcx(); let fn_ty = instance.ty(tcx, self.typing_env()); @@ -903,12 +911,10 @@ impl<'ll, 'tcx> IntrinsicCallBuilderMethods<'tcx> for Builder<'_, 'll, 'tcx> { let fn_ptr = if let Some(&llfn) = self.intrinsic_instances.borrow().get(&instance) { llfn } else { - let sym = tcx.symbol_name(instance).name; - - let llfn = if let Some(llfn) = self.get_declared_value(sym) { + let llfn = if let Some(llfn) = self.get_declared_value(intrinsic_name) { llfn } else { - intrinsic_fn(self, sym, llreturn_ty, llargument_tys, instance) + intrinsic_fn(self, intrinsic_name, llreturn_ty, llargument_tys, instance) }; self.intrinsic_instances.borrow_mut().insert(instance, llfn); @@ -953,6 +959,44 @@ impl<'ll, 'tcx> IntrinsicCallBuilderMethods<'tcx> for Builder<'_, 'll, 'tcx> { autocast(self, llret, src_ty, dest_ty) } +} + +impl<'ll, 'tcx> IntrinsicCallBuilderMethods<'tcx> for Builder<'_, 'll, 'tcx> { + fn codegen_intrinsic_call( + &mut self, + instance: ty::Instance<'tcx>, + args: &[OperandRef<'tcx, Value<'ll>>], + result_layout: ty::layout::TyAndLayout<'tcx>, + result_place: Option>>, + span: Span, + ) -> IntrinsicResult<'tcx, Value<'ll>> { + let tcx = self.tcx; + let name = tcx.intrinsic(instance.def_id()).unwrap().name; + + match name { + Intrinsic::Rustc(name) => self.codegen_rustc_intrinsic_call( + instance, + args, + result_layout, + result_place, + span, + name, + ), + Intrinsic::Backend { llvm } => { + let value = self.codegen_llvm_intrinsic_call_impl(instance, llvm.as_str(), args); + self.llvm_value_to_intrinsicresult(value, result_layout, result_place) + } + } + } + + fn codegen_llvm_intrinsic_call( + &mut self, + instance: ty::Instance<'tcx>, + args: &[OperandRef<'tcx, Self::Value>], + _is_cleanup: bool, + ) -> Self::Value { + self.codegen_llvm_intrinsic_call_impl(instance, self.tcx().symbol_name(instance).name, args) + } fn abort_immediate(&mut self) { self.call_intrinsic("llvm.trap", &[], &[]); @@ -2410,7 +2454,11 @@ fn generic_simd_intrinsic<'ll, 'tcx>( } let ty::Float(f) = in_elem.kind() else { - return_error!(InvalidMonomorphization::BasicFloatType { span, name, ty: in_ty }); + return_error!(InvalidMonomorphization::BasicFloatType { + span, + name: Intrinsic::Rustc(name), + ty: in_ty + }); }; let elem_ty = bx.cx.type_float_from_ty(*f); diff --git a/compiler/rustc_codegen_llvm/src/va_arg.rs b/compiler/rustc_codegen_llvm/src/va_arg.rs index 339a2b45714cb..997c1efe37776 100644 --- a/compiler/rustc_codegen_llvm/src/va_arg.rs +++ b/compiler/rustc_codegen_llvm/src/va_arg.rs @@ -348,7 +348,7 @@ fn emit_powerpc_va_arg<'ll, 'tcx>( bx.inbounds_ptradd(va_list_addr, bx.const_usize(1)) // fpr }; - let mut num_regs = bx.load(bx.type_i8(), num_regs_addr, dl.i8_align); + let mut num_regs = bx.load(bx.type_i8(), num_regs_addr, Align::ONE); // "Align" the register count when the type is passed as `i64`. if layout.size.bytes() == 8 && !is_passed_in_fprs { @@ -387,7 +387,7 @@ fn emit_powerpc_va_arg<'ll, 'tcx>( // Increase the used-register count. let new_num_regs = bx.add(num_regs, bx.cx.const_u8(reg_incr)); - bx.store(new_num_regs, num_regs_addr, dl.i8_align); + bx.store(new_num_regs, num_regs_addr, Align::ONE); bx.br(end); @@ -397,7 +397,7 @@ fn emit_powerpc_va_arg<'ll, 'tcx>( let mem_addr = { bx.switch_to_block(in_mem); - bx.store(bx.const_u8(max_regs), num_regs_addr, dl.i8_align); + bx.store(bx.const_u8(max_regs), num_regs_addr, Align::ONE); // Everything in the overflow area is rounded up to a size of at least 4. let overflow_area_align = Align::FOUR; diff --git a/compiler/rustc_codegen_ssa/src/base.rs b/compiler/rustc_codegen_ssa/src/base.rs index 4361e192972f4..e165bb0ce4d4d 100644 --- a/compiler/rustc_codegen_ssa/src/base.rs +++ b/compiler/rustc_codegen_ssa/src/base.rs @@ -12,6 +12,7 @@ use rustc_ast::expand::allocator::{ use rustc_attr_ir::lang_items::LangItem; use rustc_attr_ir::target::Target; use rustc_attr_ir::{DebuggerVisualizerType, EiiDecl, EiiImpl, find_attr}; +use rustc_crate_store::CrateSourceFlags; use rustc_data_structures::fx::{FxHashMap, FxIndexMap, FxIndexSet}; use rustc_data_structures::profiling::{get_resident_set_size, print_time_passes_entry}; use rustc_data_structures::sync::{IntoDynSyncSend, par_map}; @@ -646,8 +647,8 @@ pub fn collect_debugger_visualizers_transitive( tcx.crates(()) .iter() .filter(|&cnum| { - let used_crate_source = tcx.used_crate_source(*cnum); - used_crate_source.rlib.is_some() || used_crate_source.rmeta.is_some() + tcx.used_crate_source_flags(*cnum) + .intersects(CrateSourceFlags::RMETA | CrateSourceFlags::RLIB) }) .flat_map(|&cnum| tcx.debugger_visualizers(cnum)), ) diff --git a/compiler/rustc_codegen_ssa/src/diagnostics.rs b/compiler/rustc_codegen_ssa/src/diagnostics.rs index 09faa71468bf7..160eb82c11f85 100644 --- a/compiler/rustc_codegen_ssa/src/diagnostics.rs +++ b/compiler/rustc_codegen_ssa/src/diagnostics.rs @@ -12,8 +12,8 @@ use rustc_errors::{ Diag, DiagArgValue, DiagCtxtHandle, DiagSymbolList, Diagnostic, IntoDiagArg, Level, msg, }; use rustc_macros::{Diagnostic, Subdiagnostic}; -use rustc_middle::ty::Ty; use rustc_middle::ty::layout::LayoutError; +use rustc_middle::ty::{Intrinsic, Ty}; use rustc_span::{Span, Symbol}; use crate::assert_module_sources::CguReuse; @@ -724,7 +724,7 @@ pub enum InvalidMonomorphization<'tcx> { BasicIntegerType { #[primary_span] span: Span, - name: Symbol, + name: Intrinsic, ty: Ty<'tcx>, }, @@ -732,7 +732,7 @@ pub enum InvalidMonomorphization<'tcx> { BasicIntegerOrPtrType { #[primary_span] span: Span, - name: Symbol, + name: Intrinsic, ty: Ty<'tcx>, }, @@ -740,7 +740,7 @@ pub enum InvalidMonomorphization<'tcx> { BasicFloatType { #[primary_span] span: Span, - name: Symbol, + name: Intrinsic, ty: Ty<'tcx>, }, diff --git a/compiler/rustc_codegen_ssa/src/mir/block.rs b/compiler/rustc_codegen_ssa/src/mir/block.rs index 4c07eeea757cd..678d8c00c68dc 100644 --- a/compiler/rustc_codegen_ssa/src/mir/block.rs +++ b/compiler/rustc_codegen_ssa/src/mir/block.rs @@ -14,7 +14,7 @@ use rustc_middle::mir::interpret::{CTFE_ALLOC_SALT, Scalar}; use rustc_middle::mir::{self, AssertKind, InlineAsmMacro, SwitchTargets, UnwindTerminateReason}; use rustc_middle::ty::layout::{HasTyCtxt, LayoutOf, TyAndLayout, ValidityRequirement}; use rustc_middle::ty::print::{with_no_trimmed_paths, with_no_visible_paths}; -use rustc_middle::ty::{self, Instance, Ty, TypeVisitableExt}; +use rustc_middle::ty::{self, Instance, Intrinsic, Ty, TypeVisitableExt}; use rustc_session::config::OptLevel; use rustc_span::{Span, Spanned, bug, span_bug}; use rustc_target::callconv::{ @@ -902,7 +902,10 @@ impl<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>> FunctionCx<'a, 'tcx, Bx> { // Emit a panic or a no-op for `assert_*` intrinsics. // These are intrinsics that compile to panics so that we can get a message // which mentions the offending type, even from a const context. - let Some(requirement) = ValidityRequirement::from_intrinsic(intrinsic.name) else { + let Intrinsic::Rustc(name) = intrinsic.name else { + return None; + }; + let Some(requirement) = ValidityRequirement::from_rustc_intrinsic(name) else { return None; }; diff --git a/compiler/rustc_codegen_ssa/src/mir/intrinsic.rs b/compiler/rustc_codegen_ssa/src/mir/intrinsic.rs index 3504823450e75..1bfd977c2fce3 100644 --- a/compiler/rustc_codegen_ssa/src/mir/intrinsic.rs +++ b/compiler/rustc_codegen_ssa/src/mir/intrinsic.rs @@ -1,6 +1,6 @@ use rustc_abi::{Align, FieldIdx, WrappingRange}; use rustc_middle::mir::SourceInfo; -use rustc_middle::ty::{self, Ty, TyCtxt}; +use rustc_middle::ty::{self, Intrinsic, Ty, TyCtxt}; use rustc_session::config::OptLevel; use rustc_span::{ErrorGuaranteed, bug, span_bug, sym}; use rustc_target::spec::Arch; @@ -75,9 +75,27 @@ impl<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>> FunctionCx<'a, 'tcx, Bx> { let span = source_info.span; - let name = bx.tcx().item_name(instance.def_id()); + let name = bx.tcx().intrinsic(instance.def_id()).unwrap().name; let fn_args = instance.args; + let check_value = |op: OperandValue<::Value>| { + debug_assert!( + op.is_expected_variant_for_type(result_layout), + "[{name:?}] Value {op:?} is wrong for type {result_layout:?}", + ); + }; + + let Intrinsic::Rustc(name) = name else { + // Backend intrinsics go directly to the backend. + let result = + bx.codegen_intrinsic_call(instance, args, result_layout, result_place, span); + + if let IntrinsicResult::Operand(op) = result { + check_value(op); + } + return result; + }; + // If we're swapping something that's *not* an `OperandValue::Ref`, // then we can do it directly and avoid the alloca. // Otherwise, we'll let the fallback MIR body take care of it. @@ -103,12 +121,16 @@ impl<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>> FunctionCx<'a, 'tcx, Bx> { } let invalid_monomorphization_int_type = |ty| -> ErrorGuaranteed { - bx.tcx().dcx().emit_err(InvalidMonomorphization::BasicIntegerType { span, name, ty }) + bx.tcx().dcx().emit_err(InvalidMonomorphization::BasicIntegerType { + span, + name: Intrinsic::Rustc(name), + ty, + }) }; let invalid_monomorphization_int_or_ptr_type = |ty| -> ErrorGuaranteed { bx.tcx().dcx().emit_err(InvalidMonomorphization::BasicIntegerOrPtrType { span, - name, + name: Intrinsic::Rustc(name), ty, }) }; @@ -284,10 +306,12 @@ impl<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>> FunctionCx<'a, 'tcx, Bx> { bx.exactudiv(args[0].immediate(), args[1].immediate()) }), None => { - let err = bx - .tcx() - .dcx() - .emit_err(InvalidMonomorphization::BasicIntegerType { span, name, ty }); + let err = + bx.tcx().dcx().emit_err(InvalidMonomorphization::BasicIntegerType { + span, + name: Intrinsic::Rustc(name), + ty, + }); return IntrinsicResult::Err(err); } } @@ -306,7 +330,7 @@ impl<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>> FunctionCx<'a, 'tcx, Bx> { let err = bx.tcx().dcx().emit_err(InvalidMonomorphization::BasicFloatType { span, - name, + name: Intrinsic::Rustc(name), ty: args[0].layout.ty, }); return IntrinsicResult::Err(err); @@ -339,7 +363,7 @@ impl<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>> FunctionCx<'a, 'tcx, Bx> { None => { let err = bx.tcx().dcx().emit_err(InvalidMonomorphization::BasicFloatType { span, - name, + name: Intrinsic::Rustc(name), ty: args[0].layout.ty, }); return IntrinsicResult::Err(err); @@ -606,10 +630,7 @@ impl<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>> FunctionCx<'a, 'tcx, Bx> { } }; - debug_assert!( - op_val.is_expected_variant_for_type(result_layout), - "[{name:?}] Value {op_val:?} is wrong for type {result_layout:?}", - ); + check_value(op_val); IntrinsicResult::Operand(op_val) } diff --git a/compiler/rustc_codegen_ssa/src/traits/misc.rs b/compiler/rustc_codegen_ssa/src/traits/misc.rs index 08da31fd1efa2..2be250e78b80a 100644 --- a/compiler/rustc_codegen_ssa/src/traits/misc.rs +++ b/compiler/rustc_codegen_ssa/src/traits/misc.rs @@ -1,9 +1,8 @@ use std::cell::RefCell; use rustc_data_structures::fx::FxHashMap; -use rustc_middle::ty::{self, Instance, Ty}; +use rustc_middle::ty::{self, Instance, Intrinsic, Ty}; use rustc_session::{PointerAuthSchema, Session}; -use rustc_span::Symbol; use super::BackendTypes; @@ -38,5 +37,5 @@ pub trait MiscCodegenMethods<'tcx>: BackendTypes { /// when emitting code for the intrinsic `name`. /// /// This is discouraged, but here for now to simplify migration to using OperandValues - fn intrinsic_call_expects_place_always(&self, name: Symbol) -> bool; + fn intrinsic_call_expects_place_always(&self, name: Intrinsic) -> bool; } diff --git a/compiler/rustc_const_eval/src/check_consts/check.rs b/compiler/rustc_const_eval/src/check_consts/check.rs index 11f1b2a7a8210..092a6823db07c 100644 --- a/compiler/rustc_const_eval/src/check_consts/check.rs +++ b/compiler/rustc_const_eval/src/check_consts/check.rs @@ -831,7 +831,7 @@ impl<'tcx> Visitor<'tcx> for Checker<'_, 'tcx> { return; } - // Intrinsics are language primitives, not regular calls, so treat them separately. + // Non-backend intrinsics are language primitives, not regular calls, so treat them separately. if let Some(intrinsic) = tcx.intrinsic(callee) { if !tcx.is_const_fn(callee) { // Non-const intrinsic. diff --git a/compiler/rustc_const_eval/src/check_consts/ops.rs b/compiler/rustc_const_eval/src/check_consts/ops.rs index 3a1c083fa835f..b4c0b6030e371 100644 --- a/compiler/rustc_const_eval/src/check_consts/ops.rs +++ b/compiler/rustc_const_eval/src/check_consts/ops.rs @@ -11,8 +11,8 @@ use rustc_infer::traits::{ImplSource, Obligation, ObligationCause}; use rustc_middle::mir::CallSource; use rustc_middle::ty::print::{PrintTraitRefExt as _, with_no_trimmed_paths}; use rustc_middle::ty::{ - self, AssocContainer, Closure, FnDef, FnPtr, GenericArgKind, GenericArgs, Param, TraitRef, Ty, - suggest_constraining_type_param, + self, AssocContainer, Closure, FnDef, FnPtr, GenericArgKind, GenericArgs, Intrinsic, Param, + TraitRef, Ty, suggest_constraining_type_param, }; use rustc_session::diagnostics::add_feature_diagnostics; use rustc_span::{BytePos, Pos, Span, Symbol, span_bug, sym}; @@ -491,7 +491,7 @@ impl<'tcx> NonConstOp<'tcx> for CallUnstable { /// A call to an intrinsic that is just not const-callable at all. #[derive(Debug)] pub(crate) struct IntrinsicNonConst { - pub name: Symbol, + pub name: Intrinsic, } impl<'tcx> NonConstOp<'tcx> for IntrinsicNonConst { @@ -507,7 +507,7 @@ impl<'tcx> NonConstOp<'tcx> for IntrinsicNonConst { /// A call to an intrinsic that is just not const-callable at all. #[derive(Debug)] pub(crate) struct IntrinsicUnstable { - pub name: Symbol, + pub name: Intrinsic, pub feature: Symbol, pub const_stable_indirect: bool, } diff --git a/compiler/rustc_const_eval/src/const_eval/machine.rs b/compiler/rustc_const_eval/src/const_eval/machine.rs index 2ad6ee2a88a43..3e6329cfe0a12 100644 --- a/compiler/rustc_const_eval/src/const_eval/machine.rs +++ b/compiler/rustc_const_eval/src/const_eval/machine.rs @@ -14,7 +14,7 @@ use rustc_middle::mir::AssertMessage; use rustc_middle::mir::interpret::ReportedErrorInfo; use rustc_middle::query::TyCtxtAt; use rustc_middle::ty::layout::{HasTyCtxt, HasTypingEnv, TyAndLayout, ValidityRequirement}; -use rustc_middle::ty::{self, FieldInfo, ScalarInt, Ty, TyCtxt}; +use rustc_middle::ty::{self, FieldInfo, Intrinsic, ScalarInt, Ty, TyCtxt}; use rustc_middle::{mir, throw_machine_stop}; use rustc_span::{Span, Symbol, bug, span_bug, sym}; use rustc_target::callconv::FnAbi; @@ -486,7 +486,26 @@ impl<'tcx> interpret::Machine<'tcx> for CompileTimeMachine<'tcx> { if ecx.eval_intrinsic(instance, args, dest, target)? { return interp_ok(None); } - let intrinsic_name = ecx.tcx.item_name(instance.def_id()); + let intrinsic_name = ecx.tcx.intrinsic(instance.def_id()).unwrap().name; + + let do_fallback = || { + // We haven't handled the intrinsic, let's see if we can use a fallback body. + if ecx.tcx.intrinsic(instance.def_id()).unwrap().must_be_overridden { + throw_unsup_format!( + "intrinsic `{intrinsic_name}` is not supported at compile-time" + ); + } + return interp_ok(Some(ty::Instance { + def: ty::InstanceKind::Item(instance.def_id()), + args: instance.args, + })); + }; + + // Backend intrinsics are not supported in const eval except with their fallback + // bodies. + let Intrinsic::Rustc(intrinsic_name) = intrinsic_name else { + return do_fallback(); + }; // CTFE-specific intrinsics. match intrinsic_name { @@ -566,7 +585,8 @@ impl<'tcx> interpret::Machine<'tcx> for CompileTimeMachine<'tcx> { | sym::assert_zero_valid | sym::assert_mem_uninitialized_valid => { let ty = instance.args.type_at(0); - let requirement = ValidityRequirement::from_intrinsic(intrinsic_name).unwrap(); + let requirement = + ValidityRequirement::from_rustc_intrinsic(intrinsic_name).unwrap(); let should_panic = !ecx .tcx @@ -962,16 +982,7 @@ impl<'tcx> interpret::Machine<'tcx> for CompileTimeMachine<'tcx> { } _ => { - // We haven't handled the intrinsic, let's see if we can use a fallback body. - if ecx.tcx.intrinsic(instance.def_id()).unwrap().must_be_overridden { - throw_unsup_format!( - "intrinsic `{intrinsic_name}` is not supported at compile-time" - ); - } - return interp_ok(Some(ty::Instance { - def: ty::InstanceKind::Item(instance.def_id()), - args: instance.args, - })); + return do_fallback(); } } diff --git a/compiler/rustc_const_eval/src/diagnostics.rs b/compiler/rustc_const_eval/src/diagnostics.rs index f7c5d6c36cecb..13a7096d11e64 100644 --- a/compiler/rustc_const_eval/src/diagnostics.rs +++ b/compiler/rustc_const_eval/src/diagnostics.rs @@ -5,7 +5,7 @@ use rustc_errors::formatting::DiagMessageAddArg; use rustc_errors::{Diag, DiagArgValue, MultiSpan, Subdiagnostic, msg}; use rustc_hir::ConstContext; use rustc_macros::{Diagnostic, Subdiagnostic}; -use rustc_middle::ty::{Mutability, Ty}; +use rustc_middle::ty::{Intrinsic, Mutability, Ty}; use rustc_span::{Span, Symbol}; use crate::interpret::InternKind; @@ -167,7 +167,7 @@ pub(crate) struct UnstableConstTrait { pub(crate) struct UnstableIntrinsic { #[primary_span] pub span: Span, - pub name: Symbol, + pub name: Intrinsic, pub feature: Symbol, #[suggestion( "add `#![feature({$feature})]` to the crate attributes to enable", @@ -243,7 +243,7 @@ pub(crate) struct NonConstFnCall { pub(crate) struct NonConstIntrinsic { #[primary_span] pub span: Span, - pub name: Symbol, + pub name: Intrinsic, pub kind: ConstContext, } diff --git a/compiler/rustc_const_eval/src/interpret/intrinsics.rs b/compiler/rustc_const_eval/src/interpret/intrinsics.rs index d9278c1d97a5e..2c7da64def4ce 100644 --- a/compiler/rustc_const_eval/src/interpret/intrinsics.rs +++ b/compiler/rustc_const_eval/src/interpret/intrinsics.rs @@ -13,7 +13,7 @@ use rustc_ast::{IntTy, UintTy}; use rustc_middle::mir::interpret::{CTFE_ALLOC_SALT, read_target_uint, write_target_uint}; use rustc_middle::mir::{self, BinOp, ConstValue, NonDivergingIntrinsic}; use rustc_middle::ty::layout::TyAndLayout; -use rustc_middle::ty::{self, FloatTy, ScalarInt, Ty, TyCtxt, TypeVisitableExt}; +use rustc_middle::ty::{self, FloatTy, Intrinsic, ScalarInt, Ty, TyCtxt, TypeVisitableExt}; use rustc_span::{Symbol, bug, kw, span_bug, sym}; use tracing::trace; @@ -176,7 +176,12 @@ impl<'tcx, M: Machine<'tcx>> InterpCx<'tcx, M> { ret: Option, ) -> InterpResult<'tcx, bool> { let instance_args = instance.args; - let intrinsic_name = self.tcx.item_name(instance.def_id()); + let intrinsic_name = self.tcx.intrinsic(instance.def_id()).unwrap().name; + + // We only support rustc intrinsics for now. + let Intrinsic::Rustc(intrinsic_name) = intrinsic_name else { + return interp_ok(false); + }; if intrinsic_name.as_str().starts_with("atomic_") { return self.eval_atomic_intrinsic(intrinsic_name, instance_args, args, dest, ret); diff --git a/compiler/rustc_crate_store/Cargo.toml b/compiler/rustc_crate_store/Cargo.toml index 1857ae8130c10..4e965ec1c7378 100644 --- a/compiler/rustc_crate_store/Cargo.toml +++ b/compiler/rustc_crate_store/Cargo.toml @@ -5,6 +5,7 @@ edition = "2024" [dependencies] # tidy-alphabetical-start +bitflags = "2.4.1" rustc_abi = { path = "../rustc_abi" } rustc_attr_ir = { path = "../rustc_attr_ir" } rustc_data_structures = { path = "../rustc_data_structures" } diff --git a/compiler/rustc_crate_store/src/cstore.rs b/compiler/rustc_crate_store/src/cstore.rs index c8fe5562bdd59..bd674cbf33503 100644 --- a/compiler/rustc_crate_store/src/cstore.rs +++ b/compiler/rustc_crate_store/src/cstore.rs @@ -27,12 +27,47 @@ pub struct CrateSource { pub rmeta: Option, pub sdylib_interface: Option, } +/// Flags about where a crate came from on the local filesystem. +/// +/// Used to avoid introducing dependencies on absolute paths for incrementals when +/// the caller only needs to know if a field of `CrateSource` is_some. +#[derive(PartialEq, Clone, StableHash, Copy)] +pub struct CrateSourceFlags(u8); +bitflags::bitflags! { + impl CrateSourceFlags: u8 { + const DYLIB = 1 << 0; + const RLIB = 1 << 1; + const RMETA = 1 << 2; + const SDYLIB_INTERFACE = 1 << 3; + } +} +rustc_data_structures::external_bitflags_debug! { CrateSourceFlags } impl CrateSource { #[inline] pub fn paths(&self) -> impl Iterator { self.dylib.iter().chain(self.rlib.iter()).chain(self.rmeta.iter()) } + + #[inline] + pub fn flags(&self) -> CrateSourceFlags { + let mut flags = CrateSourceFlags::empty(); + + if self.dylib.is_some() { + flags |= CrateSourceFlags::DYLIB; + } + if self.rlib.is_some() { + flags |= CrateSourceFlags::RLIB; + } + if self.rmeta.is_some() { + flags |= CrateSourceFlags::RMETA; + } + if self.sdylib_interface.is_some() { + flags |= CrateSourceFlags::SDYLIB_INTERFACE; + } + + flags + } } #[derive(Encodable, BlobDecodable, Copy, Clone, Ord, PartialOrd, Eq, PartialEq, Debug)] diff --git a/compiler/rustc_expand/src/diagnostics.rs b/compiler/rustc_expand/src/diagnostics.rs index 481b2d5346300..82a28aa5e3785 100644 --- a/compiler/rustc_expand/src/diagnostics.rs +++ b/compiler/rustc_expand/src/diagnostics.rs @@ -568,16 +568,6 @@ pub(crate) struct MacroArgsBadDelimSugg { pub close: Span, } -#[derive(Diagnostic)] -#[diag("unused doc comment")] -#[help( - "to document an item produced by a macro, the macro must produce the documentation as part of its expansion" -)] -pub(crate) struct MacroCallUnusedDocComment { - #[label("rustdoc does not generate documentation for macro invocations")] - pub span: Span, -} - #[derive(Diagnostic)] #[diag( "the meaning of the `pat` fragment specifier is changing in Rust 2021, which may affect this macro" diff --git a/compiler/rustc_expand/src/expand.rs b/compiler/rustc_expand/src/expand.rs index 935532fddcc9e..d3dea34aff80e 100644 --- a/compiler/rustc_expand/src/expand.rs +++ b/compiler/rustc_expand/src/expand.rs @@ -1,7 +1,7 @@ use std::path::PathBuf; use std::rc::Rc; use std::sync::Arc; -use std::{iter, mem, slice}; +use std::{iter, mem}; use rustc_ast::mut_visit::*; use rustc_ast::tokenstream::TokenStream; @@ -23,7 +23,6 @@ use rustc_data_structures::flat_map_in_place::FlatMapInPlace; use rustc_errors::PResult; use rustc_feature::Features; use rustc_hir::def::MacroKinds; -use rustc_lint_defs::builtin::UNUSED_DOC_COMMENTS; use rustc_parse::parser::{ AllowConstBlockItems, AttemptLocalParseRecovery, CommaRecoveryMode, ForceCollect, Parser, RecoverColon, RecoverComma, Recovery, token_descr, @@ -2229,42 +2228,17 @@ impl<'a, 'b> InvocationCollector<'a, 'b> { // Run attributes through the attribute parser // since they will not be detected after macro expansion. fn check_attributes(&self, attrs: &[ast::Attribute], call: &ast::MacCall) { - let mut attrs = attrs.iter().peekable(); - let mut span: Option = None; - while let Some(attr) = attrs.next() { - AttributeParser::parse_limited_all( - self.cx.sess, - slice::from_ref(attr), - None, - AstTarget::MacroCall, - call.span(), - self.cx.current_expansion.lint_node_id, - Some(self.cx.ecfg.features), - ShouldEmit::ErrorsAndLints { recovery: Recovery::Allowed }, - Some(self.cx.resolver.registered_attr_tools()), - ); - - let current_span = if let Some(sp) = span { sp.to(attr.span) } else { attr.span }; - span = Some(current_span); - - if attrs.peek().is_some_and(|next_attr| next_attr.doc_str().is_some()) { - continue; - } - - if match &attr.kind { - AttrKind::Normal(normal) => normal.item.name() == Some(sym::doc), - AttrKind::DocComment(..) => true, - _ => false, - } { - self.cx.sess.psess.buffer_lint( - UNUSED_DOC_COMMENTS, - current_span, - self.cx.current_expansion.lint_node_id, - crate::diagnostics::MacroCallUnusedDocComment { span: attr.span }, - ); - continue; - } - } + AttributeParser::parse_limited_all( + self.cx.sess, + attrs, + None, + AstTarget::MacroCall, + call.span(), + self.cx.current_expansion.lint_node_id, + Some(self.cx.ecfg.features), + ShouldEmit::ErrorsAndLints { recovery: Recovery::Allowed }, + Some(self.cx.resolver.registered_attr_tools()), + ); } fn expand_cfg_true( diff --git a/compiler/rustc_hir_analysis/src/check/check.rs b/compiler/rustc_hir_analysis/src/check/check.rs index 495e8e5590eed..3c9a6b5697eeb 100644 --- a/compiler/rustc_hir_analysis/src/check/check.rs +++ b/compiler/rustc_hir_analysis/src/check/check.rs @@ -24,8 +24,8 @@ use rustc_middle::ty::error::TypeErrorToStringExt; use rustc_middle::ty::layout::LayoutError; use rustc_middle::ty::util::Discr; use rustc_middle::ty::{ - AdtDef, BottomUpFolder, GenericArgKind, RegionKind, TypeFoldable, TypeSuperVisitable, - TypeVisitable, TypeVisitableExt, Unnormalized, fold_regions, + AdtDef, BottomUpFolder, GenericArgKind, Intrinsic, RegionKind, TypeFoldable, + TypeSuperVisitable, TypeVisitable, TypeVisitableExt, Unnormalized, fold_regions, }; use rustc_span::sym; use rustc_target::spec::{AbiMap, AbiMapping}; @@ -835,12 +835,14 @@ pub(crate) fn check_item_type(tcx: TyCtxt<'_>, def_id: LocalDefId) -> Result<(), tcx.ensure_ok().clauses_of(def_id); tcx.ensure_ok().fn_sig(def_id); tcx.ensure_ok().codegen_fn_attrs(def_id); - if let Some(i) = tcx.intrinsic(def_id) { + if let Some(i) = tcx.intrinsic(def_id) + && let Intrinsic::Rustc(name) = i.name + { intrinsic::check_intrinsic_type( tcx, def_id, tcx.def_ident_span(def_id).unwrap(), - i.name, + name, ) } } diff --git a/compiler/rustc_hir_typeck/src/closure.rs b/compiler/rustc_hir_typeck/src/closure.rs index 07ce529f9174d..ee86b429033a4 100644 --- a/compiler/rustc_hir_typeck/src/closure.rs +++ b/compiler/rustc_hir_typeck/src/closure.rs @@ -61,6 +61,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { let (expected_sig, expected_kind) = match expected.to_option(self) { Some(ty) => self.deduce_closure_signature( self.deeply_resolve_ignoring_regions_with_obligations(ty), + closure.def_id, closure.kind, ), None => (None, None), @@ -290,9 +291,28 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { fn deduce_closure_signature( &self, expected_ty: Ty<'tcx>, + closure_def_id: LocalDefId, closure_kind: hir::ClosureKind, ) -> (Option>, Option) { match *expected_ty.kind() { + ty::Coroutine(def_id, args) + if def_id == closure_def_id.to_def_id() + && matches!( + closure_kind, + hir::ClosureKind::Coroutine(hir::CoroutineKind::Desugared( + hir::CoroutineDesugaring::Async, + hir::CoroutineSource::Closure, + )) + ) => + { + // An async closure's body is itself a coroutine. Propagate the signature + // inferred for that coroutine into its body. + let args = args.as_coroutine(); + let sig = ty::Binder::dummy( + self.tcx.mk_fn_sig_safe_rust_abi([args.resume_ty()], args.return_ty()), + ); + (Some(ExpectedSig { cause_span: None, sig }), None) + } ty::Alias(_, ty::AliasTy { kind: ty::Opaque { def_id }, args, .. }) => self .deduce_closure_signature_from_predicates( expected_ty, diff --git a/compiler/rustc_hir_typeck/src/expr.rs b/compiler/rustc_hir_typeck/src/expr.rs index 7f187180c3a06..3c8b4f125ff78 100644 --- a/compiler/rustc_hir_typeck/src/expr.rs +++ b/compiler/rustc_hir_typeck/src/expr.rs @@ -648,7 +648,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { if let ty::FnDef(did, args) = *ty.kind() { let fn_sig = ty.fn_sig(tcx); - if tcx.is_intrinsic(did, sym::transmute) { + if tcx.is_rustc_intrinsic(did, sym::transmute) { let Some(from) = fn_sig.inputs().skip_binder().get(0) else { span_bug!( tcx.def_span(did), @@ -663,7 +663,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { self.deferred_transmute_checks.borrow_mut().push((*from, to, expr.hir_id)); } if !tcx.sess.opts.unstable_opts.offload.is_empty() - && tcx.is_intrinsic(did, sym::offload) + && tcx.is_rustc_intrinsic(did, sym::offload) { let args = args.skip_binder(); let f = args.type_at(0); diff --git a/compiler/rustc_lint/src/builtin.rs b/compiler/rustc_lint/src/builtin.rs index a376252ad1038..38675220b7ad1 100644 --- a/compiler/rustc_lint/src/builtin.rs +++ b/compiler/rustc_lint/src/builtin.rs @@ -56,8 +56,7 @@ use crate::diagnostics::{ BuiltinNonShorthandFieldPatterns, BuiltinSpecialModuleNameUsed, BuiltinTrivialBounds, BuiltinTypeAliasBounds, BuiltinUngatedAsyncFnTrackCaller, BuiltinUnpermittedTypeInit, BuiltinUnpermittedTypeInitSub, BuiltinUnreachablePub, BuiltinUnsafe, BuiltinUnstableFeatures, - BuiltinUnusedDocComment, BuiltinUnusedDocCommentSub, BuiltinWhileTrue, - EqInternalMethodImplemented, InvalidAsmLabel, + BuiltinWhileTrue, EqInternalMethodImplemented, InvalidAsmLabel, }; use crate::{EarlyContext, EarlyLintPass, LateContext, LateLintPass, LintContext}; @@ -738,106 +737,6 @@ impl EarlyLintPass for AnonymousParameters { } } -fn warn_if_doc(cx: &EarlyContext<'_>, node_span: Span, node_kind: &str, attrs: &[ast::Attribute]) { - use rustc_ast::token::CommentKind; - - let mut attrs = attrs.iter().peekable(); - - // Accumulate a single span for sugared doc comments. - let mut sugared_span: Option = None; - - while let Some(attr) = attrs.next() { - let (is_doc_comment, is_doc_attribute) = match &attr.kind { - AttrKind::DocComment(..) => (true, false), - AttrKind::Normal(normal) if normal.item.path == sym::doc => (true, true), - _ => (false, false), - }; - if is_doc_comment { - sugared_span = - Some(sugared_span.map_or(attr.span, |span| span.with_hi(attr.span.hi()))); - } - - if !is_doc_attribute && attrs.peek().is_some_and(|next_attr| next_attr.is_doc_comment()) { - continue; - } - - let span = sugared_span.take().unwrap_or(attr.span); - - if is_doc_comment || is_doc_attribute { - let sub = match attr.kind { - AttrKind::DocComment(CommentKind::Line, _) | AttrKind::Normal(..) => { - BuiltinUnusedDocCommentSub::PlainHelp - } - AttrKind::DocComment(CommentKind::Block, _) => { - BuiltinUnusedDocCommentSub::BlockHelp - } - AttrKind::Synthetic(..) | AttrKind::Generated(..) => unreachable!(), - }; - cx.emit_span_lint( - UNUSED_DOC_COMMENTS, - span, - BuiltinUnusedDocComment { kind: node_kind, label: node_span, sub }, - ); - } - } -} - -impl EarlyLintPass for UnusedDocComment { - fn check_stmt(&mut self, cx: &EarlyContext<'_>, stmt: &ast::Stmt) { - let kind = match stmt.kind { - ast::StmtKind::Let(..) => "statements", - // Disabled pending discussion in #78306 - ast::StmtKind::Item(..) => return, - // expressions will be reported by `check_expr`. - ast::StmtKind::Empty - | ast::StmtKind::Semi(_) - | ast::StmtKind::Expr(_) - | ast::StmtKind::MacCall(_) => return, - }; - - warn_if_doc(cx, stmt.span, kind, stmt.kind.attrs()); - } - - fn check_arm(&mut self, cx: &EarlyContext<'_>, arm: &ast::Arm) { - if let Some(body) = &arm.body { - let arm_span = arm.pat.span.with_hi(body.span.hi()); - warn_if_doc(cx, arm_span, "match arms", &arm.attrs); - } - } - - fn check_pat(&mut self, cx: &EarlyContext<'_>, pat: &ast::Pat) { - if let ast::PatKind::Struct(_, _, fields, _) = &pat.kind { - for field in fields { - warn_if_doc(cx, field.span, "pattern fields", &field.attrs); - } - } - } - - fn check_expr(&mut self, cx: &EarlyContext<'_>, expr: &ast::Expr) { - warn_if_doc(cx, expr.span, "expressions", &expr.attrs); - - if let ExprKind::Struct(s) = &expr.kind { - for field in &s.fields { - warn_if_doc(cx, field.span, "expression fields", &field.attrs); - } - } - } - - fn check_generic_param(&mut self, cx: &EarlyContext<'_>, param: &ast::GenericParam) { - warn_if_doc(cx, param.ident.span, "generic parameters", ¶m.attrs); - } - - fn check_block(&mut self, cx: &EarlyContext<'_>, block: &ast::Block) { - warn_if_doc(cx, block.span, "blocks", block.attrs()); - } - - fn check_item(&mut self, cx: &EarlyContext<'_>, item: &ast::Item) { - if let ast::ItemKind::ForeignMod(_) = item.kind { - warn_if_doc(cx, item.span, "extern blocks", &item.attrs); - } - } -} - declare_lint! { /// The `no_mangle_const_items` lint detects any `const` items with the /// [`no_mangle` attribute]. @@ -991,7 +890,7 @@ impl<'tcx> LateLintPass<'tcx> for MutableTransmutes { } fn def_id_is_transmute(cx: &LateContext<'_>, def_id: DefId) -> bool { - cx.tcx.is_intrinsic(def_id, sym::transmute) + cx.tcx.is_rustc_intrinsic(def_id, sym::transmute) } } } diff --git a/compiler/rustc_lint/src/diagnostics.rs b/compiler/rustc_lint/src/diagnostics.rs index 2b1a8132e65e8..6bb0944a85760 100644 --- a/compiler/rustc_lint/src/diagnostics.rs +++ b/compiler/rustc_lint/src/diagnostics.rs @@ -312,24 +312,6 @@ pub(crate) struct BuiltinAnonymousParams<'a> { pub ty_snip: &'a str, } -#[derive(Diagnostic)] -#[diag("unused doc comment")] -pub(crate) struct BuiltinUnusedDocComment<'a> { - pub kind: &'a str, - #[label("rustdoc does not generate documentation for {$kind}")] - pub label: Span, - #[subdiagnostic] - pub sub: BuiltinUnusedDocCommentSub, -} - -#[derive(Subdiagnostic)] -pub(crate) enum BuiltinUnusedDocCommentSub { - #[help("use `//` for a plain comment")] - PlainHelp, - #[help("use `/* */` for a plain comment")] - BlockHelp, -} - #[derive(Diagnostic)] #[diag("const items should never be `#[no_mangle]`")] pub(crate) struct BuiltinConstNoMangle { diff --git a/compiler/rustc_lint/src/lib.rs b/compiler/rustc_lint/src/lib.rs index 97c500ba74cee..2c3365028844a 100644 --- a/compiler/rustc_lint/src/lib.rs +++ b/compiler/rustc_lint/src/lib.rs @@ -194,7 +194,6 @@ early_lint_methods!( SpecialModuleName: SpecialModuleName, UnsafeCode: UnsafeCode, UnusedBraces: UnusedBraces, - UnusedDocComment: UnusedDocComment, UnusedImportBraces: UnusedImportBraces, UnusedParens: UnusedParens::default(), WhileTrue: WhileTrue, diff --git a/compiler/rustc_lint/src/transmute.rs b/compiler/rustc_lint/src/transmute.rs index 3b269a215cb6b..de2b299d9be81 100644 --- a/compiler/rustc_lint/src/transmute.rs +++ b/compiler/rustc_lint/src/transmute.rs @@ -122,7 +122,7 @@ impl<'tcx> LateLintPass<'tcx> for CheckTransmutes { let Res::Def(DefKind::Fn, def_id) = cx.qpath_res(&qpath, callee.hir_id) else { return; }; - if !cx.tcx.is_intrinsic(def_id, sym::transmute) { + if !cx.tcx.is_rustc_intrinsic(def_id, sym::transmute) { return; }; let body_owner_def_id = cx.tcx.hir_enclosing_body_owner(expr.hir_id); diff --git a/compiler/rustc_lint_defs/src/builtin.rs b/compiler/rustc_lint_defs/src/builtin.rs index d6e4b3b0bac7b..f1bf802dad9d0 100644 --- a/compiler/rustc_lint_defs/src/builtin.rs +++ b/compiler/rustc_lint_defs/src/builtin.rs @@ -7,7 +7,7 @@ //! When removing a lint, make sure to also add a call to `register_removed` in //! compiler/rustc_lint/src/lib.rs. -use crate::{declare_lint, declare_lint_pass, fcw}; +use crate::{declare_lint, fcw}; pub mod hardwired { use super::*; @@ -148,6 +148,7 @@ pub mod hardwired { UNUSED_ASSOCIATED_TYPE_BOUNDS, UNUSED_ATTRIBUTES, UNUSED_CRATE_DEPENDENCIES, + UNUSED_DOC_COMMENTS, UNUSED_EXTERN_CRATES, UNUSED_FEATURES, UNUSED_IMPORTS, @@ -3482,8 +3483,6 @@ declare_lint! { }; } -declare_lint_pass!(UnusedDocComment => [UNUSED_DOC_COMMENTS]); - declare_lint! { /// The `missing_abi` lint detects cases where the ABI is omitted from /// `extern` declarations. diff --git a/compiler/rustc_metadata/src/dependency_format.rs b/compiler/rustc_metadata/src/dependency_format.rs index 4a6c23a10c3af..37f369d9078da 100644 --- a/compiler/rustc_metadata/src/dependency_format.rs +++ b/compiler/rustc_metadata/src/dependency_format.rs @@ -51,8 +51,8 @@ //! Additionally, the algorithm is geared towards finding *any* solution rather //! than finding a number of solutions (there are normally quite a few). -use rustc_crate_store::CrateDepKind; use rustc_crate_store::LinkagePreference::{self, RequireDynamic, RequireStatic}; +use rustc_crate_store::{CrateDepKind, CrateSourceFlags}; use rustc_data_structures::fx::{FxHashMap, FxHashSet}; use rustc_hir::def_id::{CrateNum, LOCAL_CRATE}; use rustc_index::IndexVec; @@ -148,8 +148,8 @@ fn calculate_type(tcx: TyCtxt<'_>, ty: CrateType) -> DependencyList { if tcx.crate_dep_kind(cnum).macros_only() { continue; } - let src = tcx.used_crate_source(cnum); - if src.rlib.is_some() { + + if tcx.used_crate_source_flags(cnum).contains(CrateSourceFlags::RLIB) { continue; } sess.dcx().emit_err(RlibRequired { crate_name: tcx.crate_name(cnum) }); @@ -163,8 +163,9 @@ fn calculate_type(tcx: TyCtxt<'_>, ty: CrateType) -> DependencyList { let all_dylibs = || { tcx.crates(()).iter().filter(|&&cnum| { !tcx.crate_dep_kind(cnum).macros_only() - && (tcx.used_crate_source(cnum).dylib.is_some() - || tcx.used_crate_source(cnum).sdylib_interface.is_some()) + && (tcx + .used_crate_source_flags(cnum) + .intersects(CrateSourceFlags::DYLIB | CrateSourceFlags::SDYLIB_INTERFACE)) }) }; @@ -237,12 +238,12 @@ fn calculate_type(tcx: TyCtxt<'_>, ty: CrateType) -> DependencyList { // If the crate hasn't been included yet and it's not actually required // (e.g., it's a panic runtime) then we skip it here as well. for &cnum in tcx.crates(()).iter() { - let src = tcx.used_crate_source(cnum); - if src.dylib.is_none() + let src_flags = tcx.used_crate_source_flags(cnum); + if !src_flags.contains(CrateSourceFlags::DYLIB) && !formats.contains_key(&cnum) && tcx.crate_dep_kind(cnum) == CrateDepKind::Unconditional { - assert!(src.rlib.is_some() || src.rmeta.is_some()); + assert!(src_flags.intersects(CrateSourceFlags::RLIB | CrateSourceFlags::RMETA)); info!("adding staticlib: {}", tcx.crate_name(cnum)); add_library(tcx, cnum, RequireStatic, &mut formats, &mut unavailable_as_static); ret[cnum] = Linkage::Static; @@ -268,11 +269,16 @@ fn calculate_type(tcx: TyCtxt<'_>, ty: CrateType) -> DependencyList { if cnum == LOCAL_CRATE { continue; } - let src = tcx.used_crate_source(cnum); + let src_flags = tcx.used_crate_source_flags(cnum); match *kind { Linkage::NotLinked | Linkage::IncludedFromDylib => {} - Linkage::Static if src.rlib.is_some() => continue, - Linkage::Dynamic if src.dylib.is_some() || src.sdylib_interface.is_some() => continue, + Linkage::Static if src_flags.contains(CrateSourceFlags::RLIB) => continue, + Linkage::Dynamic + if src_flags + .intersects(CrateSourceFlags::DYLIB | CrateSourceFlags::SDYLIB_INTERFACE) => + { + continue; + } kind => { let kind = match kind { Linkage::Static => "rlib", @@ -335,7 +341,7 @@ fn attempt_static(tcx: TyCtxt<'_>, unavailable: &mut Vec) -> Option { Arc::clone(&cdata.source) } + used_crate_source_flags => { cdata.source.flags() } debugger_visualizers => { cdata.get_debugger_visualizers(tcx) } exportable_items => { tcx.arena.alloc_from_iter(cdata.get_exportable_items(tcx)) } diff --git a/compiler/rustc_middle/src/queries.rs b/compiler/rustc_middle/src/queries.rs index 95b4364da4703..c869ee8ba1a7b 100644 --- a/compiler/rustc_middle/src/queries.rs +++ b/compiler/rustc_middle/src/queries.rs @@ -57,7 +57,8 @@ use rustc_attr_ir::diagnostic_items::DiagnosticItems; use rustc_attr_ir::lang_items::{LangItem, LanguageItems}; use rustc_attr_ir::{CanonicalSymbols, EiiDecl, EiiImpl, NotableTraitColor, StrippedCfgItem}; use rustc_crate_store::{ - CrateDepKind, CrateSource, ExternCrate, ForeignModule, LinkagePreference, NativeLib, + CrateDepKind, CrateSource, CrateSourceFlags, ExternCrate, ForeignModule, LinkagePreference, + NativeLib, }; use rustc_data_structures::fx::{FxIndexMap, FxIndexSet}; use rustc_data_structures::sorted_map::SortedMap; @@ -2375,6 +2376,12 @@ rustc_queries! { separate_provide_extern } + query used_crate_source_flags(_: CrateNum) -> CrateSourceFlags { + eval_always + desc { "looking at source presence in a crate" } + separate_provide_extern + } + /// Returns the debugger visualizers defined for this crate. /// NOTE: This query has to be marked `eval_always` because it reads data /// directly from disk that is not tracked anywhere else. I.e. it diff --git a/compiler/rustc_middle/src/query/erase.rs b/compiler/rustc_middle/src/query/erase.rs index cee5bf6dccb80..6e9b2dfd0df6e 100644 --- a/compiler/rustc_middle/src/query/erase.rs +++ b/compiler/rustc_middle/src/query/erase.rs @@ -224,6 +224,7 @@ impl_erasable_for_types_with_no_type_params! { Ty<'_>, bool, rustc_crate_store::CrateDepKind, + rustc_crate_store::CrateSourceFlags, rustc_data_structures::svh::Svh, rustc_hir::Constness, rustc_hir::Defaultness, diff --git a/compiler/rustc_middle/src/ty/intrinsic.rs b/compiler/rustc_middle/src/ty/intrinsic.rs index 63c2eae384da1..37e2cda1cf67e 100644 --- a/compiler/rustc_middle/src/ty/intrinsic.rs +++ b/compiler/rustc_middle/src/ty/intrinsic.rs @@ -1,12 +1,39 @@ +use std::fmt::Display; + +use rustc_errors::IntoDiagArg; use rustc_macros::{Decodable, Encodable, StableHash}; use rustc_span::Symbol; use rustc_span::def_id::DefId; use super::TyCtxt; +/// The name of an intrinsic. +#[derive(Copy, Clone, Debug, Decodable, Encodable, StableHash, PartialEq, Eq)] +pub enum Intrinsic { + /// A Rust intrinsic (common to all backends). + Rustc(Symbol), + /// A backend-specific intrinsic. For now, we only support llvm-specific intrinsics. + Backend { llvm: Symbol }, +} + +impl Display for Intrinsic { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + match self { + Intrinsic::Rustc(i) => write!(f, "{i}"), + Intrinsic::Backend { llvm } => write!(f, "{llvm}"), + } + } +} + +impl IntoDiagArg for Intrinsic { + fn into_diag_arg(self, path: &mut Option) -> rustc_errors::DiagArgValue { + self.to_string().into_diag_arg(path) + } +} + #[derive(Copy, Clone, Debug, Decodable, Encodable, StableHash)] pub struct IntrinsicDef { - pub name: Symbol, + pub name: Intrinsic, /// Whether the intrinsic has no meaningful body and all backends need to shim all calls to it. pub must_be_overridden: bool, /// Whether the intrinsic can be invoked from stable const fn (`#[rustc_intrinsic_const_stable_indirect]`). @@ -14,8 +41,8 @@ pub struct IntrinsicDef { } impl TyCtxt<'_> { - pub fn is_intrinsic(self, def_id: DefId, name: Symbol) -> bool { + pub fn is_rustc_intrinsic(self, def_id: DefId, name: Symbol) -> bool { let Some(i) = self.intrinsic(def_id) else { return false }; - i.name == name + matches!(i.name, Intrinsic::Rustc(n) if n == name) } } diff --git a/compiler/rustc_middle/src/ty/layout.rs b/compiler/rustc_middle/src/ty/layout.rs index 1f1a769665c26..57ac2b672f43c 100644 --- a/compiler/rustc_middle/src/ty/layout.rs +++ b/compiler/rustc_middle/src/ty/layout.rs @@ -223,7 +223,7 @@ pub enum ValidityRequirement { } impl ValidityRequirement { - pub fn from_intrinsic(intrinsic: Symbol) -> Option { + pub fn from_rustc_intrinsic(intrinsic: Symbol) -> Option { match intrinsic { sym::assert_inhabited => Some(Self::Inhabited), sym::assert_zero_valid => Some(Self::Zero), @@ -836,7 +836,7 @@ where ty::Adt(def, _) => def.variant(variant_index).fields.len(), _ => bug!("`ty_and_layout_for_variant` on unexpected type {}", this.ty), }; - tcx.mk_layout(LayoutData::uninhabited_variant(cx, variant_index, fields)) + tcx.mk_layout(LayoutData::uninhabited_variant(variant_index, fields)) } Variants::Multiple { .. } => { diff --git a/compiler/rustc_middle/src/ty/mod.rs b/compiler/rustc_middle/src/ty/mod.rs index 8de81ccd1e2fb..5a5213be8bda1 100644 --- a/compiler/rustc_middle/src/ty/mod.rs +++ b/compiler/rustc_middle/src/ty/mod.rs @@ -24,7 +24,7 @@ pub use adt::*; pub use assoc::*; pub use generic_args::{GenericArgKind, TermKind, *}; pub use generics::*; -pub use intrinsic::IntrinsicDef; +pub use intrinsic::{Intrinsic, IntrinsicDef}; use rustc_abi::{ Align, FieldIdx, Integer, IntegerType, ReprFlags, ReprOptions, ScalableElt, Size, VariantIdx, }; diff --git a/compiler/rustc_middle/src/ty/util.rs b/compiler/rustc_middle/src/ty/util.rs index a588114cda6ce..9a99598e3b078 100644 --- a/compiler/rustc_middle/src/ty/util.rs +++ b/compiler/rustc_middle/src/ty/util.rs @@ -26,6 +26,7 @@ use crate::middle::codegen_fn_attrs::CodegenFnAttrFlags; use crate::mir; use crate::query::Providers; use crate::traits::ObligationCause; +use crate::ty::intrinsic::Intrinsic; use crate::ty::layout::{FloatExt, IntegerExt}; use crate::ty::{ self, Asyncness, FallibleTypeFolder, GenericArgKind, GenericArgs, Ty, TyCtxt, TypeFoldable, @@ -1733,15 +1734,22 @@ pub fn doc_notable_trait(tcx: TyCtxt<'_>, def_id: DefId) -> Option<&'_ NotableTr /// the compiler to make some assumptions about its shape; if the user doesn't use a feature gate, they may /// cause an ICE that we otherwise may want to prevent. pub fn intrinsic_raw(tcx: TyCtxt<'_>, def_id: LocalDefId) -> Option { - if tcx.features().intrinsics() && find_attr!(tcx, def_id, RustcIntrinsic) { + if tcx.features().intrinsics() + // find any rustc_intrinsic attribute, possibly with a "llvm = ..." argument + && let Some(maybe_llvm) = find_attr!(tcx, def_id, RustcIntrinsic{llvm} => *llvm) + { let must_be_overridden = match tcx.hir_node_by_def_id(def_id) { hir::Node::Item(hir::Item { kind: hir::ItemKind::Fn { has_body, .. }, .. }) => { !has_body } _ => true, }; + let name = match maybe_llvm { + Some(s) => Intrinsic::Backend { llvm: s }, + None => Intrinsic::Rustc(tcx.item_name(def_id)), + }; Some(ty::IntrinsicDef { - name: tcx.item_name(def_id), + name, must_be_overridden, const_stable_indirect: find_attr!(tcx, def_id, RustcIntrinsicConstStableIndirect), }) diff --git a/compiler/rustc_mir_build/src/builder/expr/into.rs b/compiler/rustc_mir_build/src/builder/expr/into.rs index 86f781f35f60d..1f641940d10eb 100644 --- a/compiler/rustc_mir_build/src/builder/expr/into.rs +++ b/compiler/rustc_mir_build/src/builder/expr/into.rs @@ -8,7 +8,7 @@ use rustc_data_structures::thin_vec::ThinVec; use rustc_hir as hir; use rustc_middle::mir::*; use rustc_middle::thir::*; -use rustc_middle::ty::{self, CanonicalUserTypeAnnotation, Ty}; +use rustc_middle::ty::{self, CanonicalUserTypeAnnotation, Intrinsic, Ty}; use rustc_span::{DUMMY_SP, Spanned, span_bug, sym}; use rustc_trait_selection::infer::InferCtxtExt; use tracing::{debug, instrument}; @@ -407,7 +407,10 @@ impl<'a, 'tcx> Builder<'a, 'tcx> { ExprKind::Call { ty, fun, ref args, .. } if let ty::FnDef(def_id, generic_args) = *ty.kind() && let Some(intrinsic) = this.tcx.intrinsic(def_id) - && matches!(intrinsic.name, sym::write_via_move | sym::write_box_via_move) => + && matches!( + intrinsic.name, + Intrinsic::Rustc(sym::write_via_move | sym::write_box_via_move) + ) => { let generic_args = generic_args.no_bound_vars().unwrap(); // We still have to evaluate the callee expression as normal (but we don't care @@ -415,7 +418,7 @@ impl<'a, 'tcx> Builder<'a, 'tcx> { let _fun = unpack!(block = this.as_local_operand(block, fun)); match intrinsic.name { - sym::write_via_move => { + Intrinsic::Rustc(sym::write_via_move) => { // `write_via_move(ptr, val)` becomes `*ptr = val` but without any dropping. // The destination must have unit type. @@ -434,7 +437,7 @@ impl<'a, 'tcx> Builder<'a, 'tcx> { this.cfg.push_assign_unit(block, source_info, destination, this.tcx); block.unit() } - sym::write_box_via_move => { + Intrinsic::Rustc(sym::write_box_via_move) => { // The signature is: // `fn write_box_via_move(b: Box>, val: T) -> Box>`. // `write_box_via_move(b, val)` becomes diff --git a/compiler/rustc_mir_dataflow/src/rustc_peek.rs b/compiler/rustc_mir_dataflow/src/rustc_peek.rs index 0e14d1f830492..975b48fc01af7 100644 --- a/compiler/rustc_mir_dataflow/src/rustc_peek.rs +++ b/compiler/rustc_mir_dataflow/src/rustc_peek.rs @@ -1,6 +1,6 @@ use rustc_attr_ir::{RustcMirKind, find_attr}; use rustc_middle::mir::{self, Body, Local, Location}; -use rustc_middle::ty::{self, Ty, TyCtxt}; +use rustc_middle::ty::{self, Intrinsic, Ty, TyCtxt}; use rustc_span::{Span, sym}; use tracing::{debug, info}; @@ -164,7 +164,7 @@ impl PeekCall { { let fn_args = fn_args.no_bound_vars().unwrap(); - if tcx.intrinsic(def_id)?.name != sym::rustc_peek { + if tcx.intrinsic(def_id)?.name != Intrinsic::Rustc(sym::rustc_peek) { return None; } diff --git a/compiler/rustc_mir_transform/src/cross_crate_inline.rs b/compiler/rustc_mir_transform/src/cross_crate_inline.rs index 53d58439b0434..a57007d9738a8 100644 --- a/compiler/rustc_mir_transform/src/cross_crate_inline.rs +++ b/compiler/rustc_mir_transform/src/cross_crate_inline.rs @@ -35,7 +35,7 @@ fn cross_crate_inlinable(tcx: TyCtxt<'_>, def_id: LocalDefId) -> bool { return true; } - if find_attr!(tcx, def_id, RustcIntrinsic) { + if find_attr!(tcx, def_id, RustcIntrinsic { .. }) { // Intrinsic fallback bodies are always cross-crate inlineable. // To ensure that the MIR inliner doesn't cluelessly try to inline fallback // bodies even when the backend would implement something better, we stop @@ -163,7 +163,7 @@ impl<'tcx> Visitor<'tcx> for CostChecker<'_, 'tcx> { // cross-crate-inlining. Adding a broad exception for all intrinsics benchmarks well // and seems more sustainable than an ever-growing list of intrinsics to ignore. if let Some((fn_def_id, _)) = func.const_fn_def() - && find_attr!(tcx, fn_def_id, RustcIntrinsic) + && find_attr!(tcx, fn_def_id, RustcIntrinsic { .. }) { return; } diff --git a/compiler/rustc_mir_transform/src/inline.rs b/compiler/rustc_mir_transform/src/inline.rs index c932d8c22c6e2..aaf2a3c1fec0a 100644 --- a/compiler/rustc_mir_transform/src/inline.rs +++ b/compiler/rustc_mir_transform/src/inline.rs @@ -14,7 +14,8 @@ use rustc_middle::middle::codegen_fn_attrs::CodegenFnAttrs; use rustc_middle::mir::visit::*; use rustc_middle::mir::*; use rustc_middle::ty::{ - self, Instance, InstanceKind, ShimKind, Ty, TyCtxt, TypeFlags, TypeVisitableExt, Unnormalized, + self, Instance, InstanceKind, Intrinsic, ShimKind, Ty, TyCtxt, TypeFlags, TypeVisitableExt, + Unnormalized, }; use rustc_session::config::{DebugInfo, OptLevel}; use rustc_span::{Spanned, bug}; @@ -561,8 +562,17 @@ fn resolve_callsite<'tcx, I: Inliner<'tcx>>( if intrinsic.must_be_overridden { return None; // intrinsic without fallback body } - if !tcx.sess.fallback_intrinsics.contains(&intrinsic.name) { - return None; // intrinsic that the backend may want to overwrite + match intrinsic.name { + // intrinsics that the backend may want to overwrite + Intrinsic::Rustc(name) + if !tcx.sess.fallback_rustc_intrinsics.contains(&name) => + { + return None; + } + Intrinsic::Backend { .. } => { + return None; + } + _ => {} } // The callee is the fallback body. debug!("callsite is fallback body: {def_id:?}"); diff --git a/compiler/rustc_mir_transform/src/inline/cycle.rs b/compiler/rustc_mir_transform/src/inline/cycle.rs index 77ddecabc291f..ecabb3bef0f1e 100644 --- a/compiler/rustc_mir_transform/src/inline/cycle.rs +++ b/compiler/rustc_mir_transform/src/inline/cycle.rs @@ -212,7 +212,7 @@ pub(crate) fn mir_inliner_callees<'tcx>( let ty::FnDef(def_id, generic_args) = ty.kind() else { continue; }; - let call = if tcx.is_intrinsic(*def_id, sym::const_eval_select) { + let call = if tcx.is_rustc_intrinsic(*def_id, sym::const_eval_select) { let func = &call_args[2].node; let ty = func.ty(&body.local_decls, tcx); let ty::FnDef(def_id, generic_args) = ty.kind() else { diff --git a/compiler/rustc_mir_transform/src/instsimplify.rs b/compiler/rustc_mir_transform/src/instsimplify.rs index 11ce25f2f5d7d..6c9c969dbc534 100644 --- a/compiler/rustc_mir_transform/src/instsimplify.rs +++ b/compiler/rustc_mir_transform/src/instsimplify.rs @@ -7,8 +7,8 @@ use rustc_index::IndexVec; use rustc_middle::mir::visit::MutVisitor; use rustc_middle::mir::*; use rustc_middle::ty::layout::{IntegerExt, ValidityRequirement}; -use rustc_middle::ty::{self, GenericArgs, Ty, TyCtxt, layout}; -use rustc_span::{Symbol, bug, sym}; +use rustc_middle::ty::{self, GenericArgs, Intrinsic, Ty, TyCtxt, layout}; +use rustc_span::{bug, sym}; use crate::PassPolicy; use crate::simplify::simplify_duplicate_switch_targets; @@ -281,9 +281,9 @@ impl<'tcx> InstSimplifyContext<'_, 'tcx> { && args.len() == 1 && let Some((fn_def_id, generics)) = func.const_fn_def() { - let lang_item = if self.tcx.is_intrinsic(fn_def_id, sym::size_of_val) { + let lang_item = if self.tcx.is_rustc_intrinsic(fn_def_id, sym::size_of_val) { LangItem::SizeOf - } else if self.tcx.is_intrinsic(fn_def_id, sym::align_of_val) { + } else if self.tcx.is_rustc_intrinsic(fn_def_id, sym::align_of_val) { LangItem::AlignOf } else { return; @@ -333,7 +333,7 @@ impl<'tcx> InstSimplifyContext<'_, 'tcx> { } = &terminator.kind && args.len() == 2 && let Some((fn_def_id, generics)) = func.const_fn_def() - && tcx.is_intrinsic(fn_def_id, sym::raw_eq) + && tcx.is_rustc_intrinsic(fn_def_id, sym::raw_eq) && let generic_ty = generics.type_at(0) && let Ok(layout) = tcx.layout_of(self.typing_env.as_query_input(generic_ty)) && let Ok(integer) = Integer::from_size(layout.size) @@ -452,9 +452,10 @@ fn intrinsic_assert_panics<'tcx>( tcx: TyCtxt<'tcx>, typing_env: ty::TypingEnv<'tcx>, arg: ty::GenericArg<'tcx>, - intrinsic_name: Symbol, + intrinsic_name: Intrinsic, ) -> Option { - let requirement = ValidityRequirement::from_intrinsic(intrinsic_name)?; + let Intrinsic::Rustc(intrinsic_name) = intrinsic_name else { return None }; + let requirement = ValidityRequirement::from_rustc_intrinsic(intrinsic_name)?; let ty = arg.expect_ty(); Some(!tcx.check_validity_requirement((requirement, typing_env.as_query_input(ty))).ok()?) } @@ -462,7 +463,7 @@ fn intrinsic_assert_panics<'tcx>( fn resolve_rust_intrinsic<'tcx>( tcx: TyCtxt<'tcx>, func_ty: Ty<'tcx>, -) -> Option<(Symbol, GenericArgs<'tcx>)> { +) -> Option<(Intrinsic, GenericArgs<'tcx>)> { let ty::FnDef(def_id, args) = *func_ty.kind() else { return None }; let intrinsic = tcx.intrinsic(def_id)?; Some((intrinsic.name, args.no_bound_vars().unwrap())) diff --git a/compiler/rustc_mir_transform/src/lib.rs b/compiler/rustc_mir_transform/src/lib.rs index b3d762c18cd26..e8788854a8d82 100644 --- a/compiler/rustc_mir_transform/src/lib.rs +++ b/compiler/rustc_mir_transform/src/lib.rs @@ -258,7 +258,7 @@ fn remap_mir_for_const_eval_select<'tcx>( fn_span, .. } if let ty::FnDef(def_id, _) = *const_.ty().kind() - && tcx.is_intrinsic(def_id, sym::const_eval_select) => + && tcx.is_rustc_intrinsic(def_id, sym::const_eval_select) => { let Ok([tupled_args, called_in_const, called_at_rt]) = take_array(args) else { unreachable!() diff --git a/compiler/rustc_mir_transform/src/lower_intrinsics.rs b/compiler/rustc_mir_transform/src/lower_intrinsics.rs index 369ef0a6849bc..b7312e1f76b13 100644 --- a/compiler/rustc_mir_transform/src/lower_intrinsics.rs +++ b/compiler/rustc_mir_transform/src/lower_intrinsics.rs @@ -1,7 +1,7 @@ //! Lowers intrinsic calls use rustc_middle::mir::*; -use rustc_middle::ty::{self, TyCtxt}; +use rustc_middle::ty::{self, Intrinsic, TyCtxt}; use rustc_span::{bug, span_bug, sym}; use crate::{PassPolicy, take_array}; @@ -17,14 +17,15 @@ impl<'tcx> crate::MirPass<'tcx> for LowerIntrinsics { &mut terminator.kind && let ty::FnDef(def_id, generic_args) = *func.ty(local_decls, tcx).kind() && let Some(intrinsic) = tcx.intrinsic(def_id) + && let Intrinsic::Rustc(name) = intrinsic.name { let generic_args = generic_args.no_bound_vars().unwrap(); - match intrinsic.name { + match name { sym::unreachable => { terminator.kind = TerminatorKind::Unreachable; } sym::ub_checks | sym::overflow_checks | sym::contract_checks => { - let op = match intrinsic.name { + let op = match name { sym::ub_checks => RuntimeChecks::UbChecks, sym::contract_checks => RuntimeChecks::ContractChecks, sym::overflow_checks => RuntimeChecks::OverflowChecks, @@ -126,9 +127,9 @@ impl<'tcx> crate::MirPass<'tcx> for LowerIntrinsics { | sym::unchecked_shr => { let target = target.unwrap(); let Ok([lhs, rhs]) = take_array(args) else { - bug!("Wrong arguments for {} intrinsic", intrinsic.name); + bug!("Wrong arguments for {} intrinsic", name); }; - let bin_op = match intrinsic.name { + let bin_op = match name { sym::wrapping_add => BinOp::Add, sym::wrapping_sub => BinOp::Sub, sym::wrapping_mul => BinOp::Mul, @@ -154,9 +155,9 @@ impl<'tcx> crate::MirPass<'tcx> for LowerIntrinsics { sym::add_with_overflow | sym::sub_with_overflow | sym::mul_with_overflow => { let target = target.unwrap(); let Ok([lhs, rhs]) = take_array(args) else { - bug!("Wrong arguments for {} intrinsic", intrinsic.name); + bug!("Wrong arguments for {} intrinsic", name); }; - let bin_op = match intrinsic.name { + let bin_op = match name { sym::add_with_overflow => BinOp::AddWithOverflow, sym::sub_with_overflow => BinOp::SubWithOverflow, sym::mul_with_overflow => BinOp::MulWithOverflow, diff --git a/compiler/rustc_monomorphize/src/collector.rs b/compiler/rustc_monomorphize/src/collector.rs index 9833b6fafdaf8..8acb3c2d9ff8e 100644 --- a/compiler/rustc_monomorphize/src/collector.rs +++ b/compiler/rustc_monomorphize/src/collector.rs @@ -225,8 +225,8 @@ use rustc_middle::query::TyCtxtAt; use rustc_middle::ty::adjustment::{CustomCoerceUnsized, PointerCoercion}; use rustc_middle::ty::layout::ValidityRequirement; use rustc_middle::ty::{ - self, GenericArgs, GenericParamDefKind, Instance, InstanceKind, ShimKind, Ty, TyCtxt, - TypeFoldable, TypeVisitable, TypeVisitableExt, TypeVisitor, Unnormalized, VtblEntry, + self, GenericArgs, GenericParamDefKind, Instance, InstanceKind, Intrinsic, ShimKind, Ty, + TyCtxt, TypeFoldable, TypeVisitable, TypeVisitableExt, TypeVisitor, Unnormalized, VtblEntry, }; use rustc_middle::util::Providers; use rustc_session::config::{DebugInfo, EntryFnType, Offload}; @@ -869,7 +869,7 @@ impl<'a, 'tcx> MirVisitor<'tcx> for MirUsedCollector<'a, 'tcx> { ); if let ty::FnDef(def_id, _) = *callee_ty.kind() - && self.tcx.is_intrinsic(def_id, rustc_span::sym::offload) + && self.tcx.is_rustc_intrinsic(def_id, rustc_span::sym::offload) && let Some(kernel) = args.first() { let kernel_ty = kernel.node.ty(self.body, self.tcx); @@ -1004,7 +1004,14 @@ fn visit_instance_use<'tcx>( return; } if let Some(intrinsic) = tcx.intrinsic(instance.def_id()) { - if let Some(_requirement) = ValidityRequirement::from_intrinsic(intrinsic.name) { + let intrinsic_is_replaced = if let Intrinsic::Rustc(name) = intrinsic.name { + tcx.sess.replaced_rustc_intrinsics.contains(&name) + } else { + false + }; + if let Intrinsic::Rustc(name) = intrinsic.name + && let Some(_requirement) = ValidityRequirement::from_rustc_intrinsic(name) + { // The intrinsics assert_inhabited, assert_zero_valid, and assert_mem_uninitialized_valid will // be lowered in codegen to nothing or a call to panic_nounwind. So if we encounter any // of those intrinsics, we need to include a mono item for panic_nounwind, else we may try to @@ -1015,8 +1022,7 @@ fn visit_instance_use<'tcx>( output.push(create_fn_mono_item(tcx, panic_instance, source)); } } else if !intrinsic.must_be_overridden - && (tcx.sess.opts.unstable_opts.force_intrinsic_fallback - || !tcx.sess.replaced_intrinsics.contains(&intrinsic.name)) + && (tcx.sess.opts.unstable_opts.force_intrinsic_fallback || !intrinsic_is_replaced) { // Codegen the fallback body of intrinsics with fallback bodies. // We have to skip this otherwise as there's no body to codegen. diff --git a/compiler/rustc_parse/src/parser/path.rs b/compiler/rustc_parse/src/parser/path.rs index 5fe796d08cb1e..139e3d31cce8b 100644 --- a/compiler/rustc_parse/src/parser/path.rs +++ b/compiler/rustc_parse/src/parser/path.rs @@ -488,19 +488,18 @@ impl<'a> Parser<'a> { Err(error) => return Err(error), }; let inputs_span = lo.to(self.prev_token.span); + let mut span = inputs_span; + if self.token == token::RArrow { + span = span.to(self.token.span); + } let output = self.parse_ret_ty(AllowPlus::No, RecoverQPath::No, RecoverReturnSign::No)?; - let span = ident.span.to(self.prev_token.span); + if let ast::FnRetTy::Ty(ret_ty) = &output { + span = span.to(ret_ty.span); + } ParenthesizedArgs { span, inputs, inputs_span, output }.into() }; - - match &args { - GenericArgs::Parenthesized(data) => { - chain_span(path_span, data.inputs_span); - chain_span(path_span, data.output.span()); - } - _ => chain_span(path_span, args.span()), - } + chain_span(path_span, args.span()); PathSegment { ident, args: Some(args), id: ast::DUMMY_NODE_ID } } else { diff --git a/compiler/rustc_parse/src/parser/ty.rs b/compiler/rustc_parse/src/parser/ty.rs index f09faad96e16a..f3e9dc00cd5ed 100644 --- a/compiler/rustc_parse/src/parser/ty.rs +++ b/compiler/rustc_parse/src/parser/ty.rs @@ -1671,7 +1671,7 @@ impl<'a> Parser<'a> { } }; let args = ast::ParenthesizedArgs { - span: fn_path_segment.span().to(self.prev_token.span), + span: inputs_lo.to(self.prev_token.span), inputs, inputs_span, output, diff --git a/compiler/rustc_passes/src/check_attr.rs b/compiler/rustc_passes/src/check_attr.rs index 6ba7c81333f40..1c177071d37c0 100644 --- a/compiler/rustc_passes/src/check_attr.rs +++ b/compiler/rustc_passes/src/check_attr.rs @@ -346,7 +346,7 @@ impl<'tcx> CheckAttrVisitor<'tcx> { AttributeKind::RustcIfThisChanged(..) => (), AttributeKind::RustcInheritOverflowChecks => (), AttributeKind::RustcInsignificantDtor => (), - AttributeKind::RustcIntrinsic => (), + AttributeKind::RustcIntrinsic { .. } => (), AttributeKind::RustcIntrinsicConstStableIndirect => (), AttributeKind::RustcLegacyConstGenerics { .. } => (), AttributeKind::RustcLintOptDenyFieldAccess { .. } => (), diff --git a/compiler/rustc_public_bridge/src/context/impls.rs b/compiler/rustc_public_bridge/src/context/impls.rs index 945331d14b073..8c9c6ec3001c2 100644 --- a/compiler/rustc_public_bridge/src/context/impls.rs +++ b/compiler/rustc_public_bridge/src/context/impls.rs @@ -18,9 +18,9 @@ use rustc_middle::ty::print::{ use rustc_middle::ty::util::Discr; use rustc_middle::ty::{ AdtDef, AdtKind, AssocItem, Binder, ClosureKind, CoroutineArgsExt, EarlyBinder, - ExistentialTraitRef, FnSig, GenericArgs, Instance, InstanceKind, IntrinsicDef, List, PolyFnSig, - ScalarInt, TraitDef, TraitRef, Ty, TyCtxt, TyKind, TypeVisitableExt, UintTy, ValTree, - VariantDef, VtblEntry, + ExistentialTraitRef, FnSig, GenericArgs, Instance, InstanceKind, Intrinsic, IntrinsicDef, List, + PolyFnSig, ScalarInt, TraitDef, TraitRef, Ty, TyCtxt, TyKind, TypeVisitableExt, UintTy, + ValTree, VariantDef, VtblEntry, }; use rustc_middle::{mir, ty}; use rustc_span::def_id::{CrateNum, DefId, LOCAL_CRATE}; @@ -400,7 +400,11 @@ impl<'tcx, B: Bridge> CompilerCtxt<'tcx, B> { /// Retrieve the plain function name of an intrinsic. pub fn intrinsic_name(&self, def_id: DefId) -> String { - self.tcx.intrinsic(def_id).unwrap().name.to_string() + match self.tcx.intrinsic(def_id).unwrap().name { + Intrinsic::Rustc(s) => s, + Intrinsic::Backend { llvm } => llvm, + } + .to_string() } /// Retrieve the closure signature for the given generic arguments. diff --git a/compiler/rustc_resolve/src/build_reduced_graph.rs b/compiler/rustc_resolve/src/build_reduced_graph.rs index 53bf60d038123..11fde009f9a7c 100644 --- a/compiler/rustc_resolve/src/build_reduced_graph.rs +++ b/compiler/rustc_resolve/src/build_reduced_graph.rs @@ -1248,7 +1248,7 @@ impl<'a, 'ra, 'tcx> DefCollector<'a, 'ra, 'tcx> { continue; } - if !attr.is_word() { + if !attr.get_normal_item().is_word() { self.r.dcx().emit_err(diagnostics::ArgumentsMacroUseNotAllowed { span: attr.span }); } return true; diff --git a/compiler/rustc_session/src/config/cfg.rs b/compiler/rustc_session/src/config/cfg.rs index 4d74cc543b8b8..b6e03c16f6a5c 100644 --- a/compiler/rustc_session/src/config/cfg.rs +++ b/compiler/rustc_session/src/config/cfg.rs @@ -274,7 +274,7 @@ pub(crate) fn default_configuration(sess: &Session) -> Cfg { sess.target.atomic_widths(cpu) }; for (i, align) in [ - (8, layout.i8_align), + (8, Align::ONE), (16, layout.i16_align), (32, layout.i32_align), (64, layout.i64_align), diff --git a/compiler/rustc_session/src/session.rs b/compiler/rustc_session/src/session.rs index f829877d95857..2b23284c55f57 100644 --- a/compiler/rustc_session/src/session.rs +++ b/compiler/rustc_session/src/session.rs @@ -440,10 +440,10 @@ pub struct CodegenBackendInit { pub global_backend_features: Vec, /// See `Session::replaced_intrinsics`. - pub replaced_intrinsics: Vec, + pub replaced_rustc_intrinsics: Vec, /// See `Session::fallback_intrinsics`. - pub fallback_intrinsics: Vec, + pub fallback_rustc_intrinsics: Vec, /// See `Session::thin_lto_supported`. pub thin_lto_supported: bool = true, @@ -534,11 +534,11 @@ pub struct Session { /// A list of all intrinsics that the current codegen backend definitely replaces with its own /// implementations, which means their fallback bodies do not need to be monomorphized. - pub replaced_intrinsics: FxHashSet, + pub replaced_rustc_intrinsics: FxHashSet, /// A list of all intrinsics that the current codegen backend definitely does *not* replace /// with its own implementations, which means their fallback bodies can be MIR-inlined. - pub fallback_intrinsics: FxHashSet, + pub fallback_rustc_intrinsics: FxHashSet, /// Does the codegen backend support ThinLTO? pub thin_lto_supported: bool, @@ -1497,8 +1497,8 @@ pub fn build_session( let CodegenBackendInit { global_backend_features, - replaced_intrinsics, - fallback_intrinsics, + replaced_rustc_intrinsics: replaced_intrinsics, + fallback_rustc_intrinsics: fallback_intrinsics, thin_lto_supported, } = codegen_backend_init; @@ -1529,8 +1529,8 @@ pub fn build_session( target_filesearch, host_filesearch, wasm_proc_macro_filesearch, - replaced_intrinsics: FxHashSet::from_iter(replaced_intrinsics), - fallback_intrinsics: FxHashSet::from_iter(fallback_intrinsics), + replaced_rustc_intrinsics: FxHashSet::from_iter(replaced_intrinsics), + fallback_rustc_intrinsics: FxHashSet::from_iter(fallback_intrinsics), thin_lto_supported, mir_opt_bisect_eval_count: AtomicUsize::new(0), removed_rustc_main_attr: AtomicBool::new(false), diff --git a/compiler/rustc_span/src/symbol.rs b/compiler/rustc_span/src/symbol.rs index 869c4a281f7f5..d53e8c7d25482 100644 --- a/compiler/rustc_span/src/symbol.rs +++ b/compiler/rustc_span/src/symbol.rs @@ -1089,6 +1089,7 @@ symbols! { generator_clone, generators, generic_arg_infer, + generic_args, generic_assert, generic_associated_types, generic_associated_types_extended, @@ -1263,6 +1264,7 @@ symbols! { lint_reasons, literal, little, big, + llvm, load, loaded_from_disk, local, diff --git a/compiler/rustc_ty_utils/src/layout.rs b/compiler/rustc_ty_utils/src/layout.rs index 6d1a9e2d8befb..6263c8dc5d6ec 100644 --- a/compiler/rustc_ty_utils/src/layout.rs +++ b/compiler/rustc_ty_utils/src/layout.rs @@ -432,7 +432,7 @@ fn layout_of_uncached<'tcx>( } // The never type. - ty::Never => tcx.mk_layout(LayoutData::never_type(cx)), + ty::Never => tcx.mk_layout(LayoutData::never_type()), // Potentially-wide pointers. ty::Ref(_, pointee, _) | ty::RawPtr(pointee, _) => { @@ -543,7 +543,7 @@ fn layout_of_uncached<'tcx>( // Odd unit types. ty::FnDef(..) | ty::Dynamic(_, _) | ty::Foreign(..) => { let sized = matches!(ty.kind(), ty::FnDef(..)); - tcx.mk_layout(LayoutData::unit(cx, sized)) + tcx.mk_layout(LayoutData::unit(sized)) } ty::Coroutine(def_id, args) => { diff --git a/library/std/src/lib.rs b/library/std/src/lib.rs index a3df4dcd559e3..192f1931fb69d 100644 --- a/library/std/src/lib.rs +++ b/library/std/src/lib.rs @@ -712,6 +712,8 @@ pub mod arch { pub use std_detect::is_arm_feature_detected; #[stable(feature = "stdarch_loongarch_feature", since = "1.89.0")] pub use std_detect::is_loongarch_feature_detected; + #[unstable(feature = "stdarch_mips_feature_detection", issue = "111188")] + pub use std_detect::is_mips_feature_detected; #[unstable(feature = "stdarch_powerpc_feature_detection", issue = "111191")] pub use std_detect::is_powerpc_feature_detected; #[stable(feature = "riscv_ratified", since = "1.78.0")] @@ -720,8 +722,6 @@ pub mod arch { pub use std_detect::is_s390x_feature_detected; #[stable(feature = "simd_x86", since = "1.27.0")] pub use std_detect::is_x86_feature_detected; - #[unstable(feature = "stdarch_mips_feature_detection", issue = "111188")] - pub use std_detect::{is_mips_feature_detected, is_mips64_feature_detected}; } // This was stabilized in the crate root so we have to keep it there. diff --git a/library/std_detect/src/detect/arch/mips.rs b/library/std_detect/src/detect/arch/mips.rs index 9e1960eb96da5..17435c9d8f50f 100644 --- a/library/std_detect/src/detect/arch/mips.rs +++ b/library/std_detect/src/detect/arch/mips.rs @@ -2,7 +2,12 @@ features! { @TARGET: mips; - @CFG: target_arch = "mips"; + @CFG: any( + target_arch = "mips", + target_arch = "mips32r6", + target_arch = "mips64", + target_arch = "mips64r6" + ); @MACRO_NAME: is_mips_feature_detected; @MACRO_ATTRS: /// Check for the presence of a CPU feature at runtime. diff --git a/library/std_detect/src/detect/arch/mips64.rs b/library/std_detect/src/detect/arch/mips64.rs deleted file mode 100644 index 2bb44ba6e2b39..0000000000000 --- a/library/std_detect/src/detect/arch/mips64.rs +++ /dev/null @@ -1,15 +0,0 @@ -//! Run-time feature detection on MIPS64. - -features! { - @TARGET: mips64; - @CFG: target_arch = "mips64"; - @MACRO_NAME: is_mips64_feature_detected; - @MACRO_ATTRS: - /// Check for the presence of a CPU feature at runtime. - /// - /// When the feature is known to be enabled at compile time (e.g. via `-Ctarget-feature`) - /// the macro expands to `true`. - #[unstable(feature = "stdarch_mips_feature_detection", issue = "111188")] - @FEATURE: #[unstable(feature = "stdarch_mips_feature_detection", issue = "111188")] msa: "msa"; - /// MIPS SIMD Architecture (MSA) -} diff --git a/library/std_detect/src/detect/arch/mod.rs b/library/std_detect/src/detect/arch/mod.rs index 2c0b464e32beb..7e21f2986e6a4 100644 --- a/library/std_detect/src/detect/arch/mod.rs +++ b/library/std_detect/src/detect/arch/mod.rs @@ -14,8 +14,6 @@ mod powerpc; #[macro_use] mod mips; #[macro_use] -mod mips64; -#[macro_use] mod loongarch; #[macro_use] mod s390x; @@ -41,14 +39,15 @@ cfg_select! { pub use powerpc::__is_feature_detected; pub(crate) use powerpc::Feature; } - target_arch = "mips" => { + any( + target_arch = "mips", + target_arch = "mips32r6", + target_arch = "mips64", + target_arch = "mips64r6" + ) => { pub use mips::__is_feature_detected; pub(crate) use mips::Feature; } - target_arch = "mips64" => { - pub use mips64::__is_feature_detected; - pub(crate) use mips64::Feature; - } any(target_arch = "loongarch32", target_arch = "loongarch64") => { pub use loongarch::__is_feature_detected; pub(crate) use loongarch::Feature; diff --git a/library/std_detect/src/lib.rs b/library/std_detect/src/lib.rs index d5805875ad9d6..fd76ed55bc056 100644 --- a/library/std_detect/src/lib.rs +++ b/library/std_detect/src/lib.rs @@ -8,7 +8,6 @@ //! * `aarch64`: [`is_aarch64_feature_detected`] //! * `riscv`: [`is_riscv_feature_detected`] //! * `mips`: [`is_mips_feature_detected`] -//! * `mips64`: [`is_mips64_feature_detected`] //! * `powerpc`: [`is_powerpc_feature_detected`] //! * `loongarch`: [`is_loongarch_feature_detected`] //! * `s390x`: [`is_s390x_feature_detected`] diff --git a/library/stdarch/crates/simd-test-macro/src/lib.rs b/library/stdarch/crates/simd-test-macro/src/lib.rs index ee11fb5c0664b..286b36d3dd249 100644 --- a/library/stdarch/crates/simd-test-macro/src/lib.rs +++ b/library/stdarch/crates/simd-test-macro/src/lib.rs @@ -140,12 +140,14 @@ pub fn simd_test( target_arch = "s390x" => { use std::arch::is_s390x_feature_detected as test_macro; } - any(target_arch = "mips", target_arch = "mips32r6") => { + any( + target_arch = "mips", + target_arch = "mips32r6" + target_arch = "mips64", + target_arch = "mips64r6", + ) => { use std::arch::is_mips_feature_detected as test_macro; } - any(target_arch = "mips64", target_arch = "mips64r6") => { - use std::arch::is_mips64_feature_detected as test_macro; - } _ => compile_error!("unknown target; need to update simd-test-macro"), } diff --git a/src/tools/clippy/clippy_lints/src/attrs/allow_attributes.rs b/src/tools/clippy/clippy_lints/src/attrs/allow_attributes.rs index 01d442133ccf0..7c185702f3194 100644 --- a/src/tools/clippy/clippy_lints/src/attrs/allow_attributes.rs +++ b/src/tools/clippy/clippy_lints/src/attrs/allow_attributes.rs @@ -8,10 +8,10 @@ use rustc_lint::EarlyContext; // Separate each crate's features. pub fn check<'cx>(cx: &EarlyContext<'cx>, attr: &'cx Attribute) { if let AttrStyle::Outer = attr.style - && let Some(path_span) = attr.path_span() && !attr.span.from_expansion() && !is_from_proc_macro(cx, attr) { + let path_span = attr.get_normal_item().path.span; #[expect(clippy::collapsible_span_lint_calls, reason = "rust-clippy#7797")] span_lint_and_then(cx, ALLOW_ATTRIBUTES, path_span, "#[allow] attribute found", |diag| { diag.span_suggestion(path_span, "replace it with", "expect", Applicability::MachineApplicable); diff --git a/src/tools/clippy/clippy_lints/src/loops/empty_loop.rs b/src/tools/clippy/clippy_lints/src/loops/empty_loop.rs index 803b3ed7cba13..86b5a515c12c2 100644 --- a/src/tools/clippy/clippy_lints/src/loops/empty_loop.rs +++ b/src/tools/clippy/clippy_lints/src/loops/empty_loop.rs @@ -11,7 +11,7 @@ pub(super) fn check(cx: &LateContext<'_>, expr: &Expr<'_>, loop_block: &Block<'_ if let Node::Item(parent_node) = cx.tcx.hir_node(parent_hir_id) && matches!(parent_node.kind, ItemKind::Fn { .. }) && let attrs = cx.tcx.hir_attrs(parent_hir_id) - && find_attr!(attrs, RustcIntrinsic) + && find_attr!(attrs, RustcIntrinsic { .. }) { // Intrinsic functions are expanded into an empty loop when lowering the AST // to simplify the job of later passes which might expect any function to have a body. diff --git a/src/tools/clippy/clippy_utils/src/attrs.rs b/src/tools/clippy/clippy_utils/src/attrs.rs index fbb3d65238a0a..be9d6761f3625 100644 --- a/src/tools/clippy/clippy_utils/src/attrs.rs +++ b/src/tools/clippy/clippy_utils/src/attrs.rs @@ -2,6 +2,7 @@ use crate::source::SpanExt as _; use crate::{sym, tokenize_with_text}; +use rustc_ast::AttrKind; use rustc_attr_ir::{AttrArgs, find_attr}; use rustc_errors::Applicability; use rustc_hir::def_id::DefId; @@ -14,14 +15,14 @@ use std::str::FromStr as _; /// Validates a single clippy attribute and emits errors for unknown or deprecated ones. pub fn check_clippy_attr(sess: &Session, attr: &rustc_ast::ast::Attribute) { - if let [clippy, segment2] = &*attr.path() - && *clippy == sym::clippy + let AttrKind::Normal(normal) = &attr.kind else { return }; + let attr_item = &normal.item; + if let [clippy, segment2] = &*attr_item.path.segments + && clippy.ident.name == sym::clippy { - let path_span = attr - .path_span() - .expect("Clippy attributes are tool attributes, so they have a span"); + let path_span = attr_item.path.span; - match *segment2 { + match segment2.ident.name { sym::cyclomatic_complexity => { sess.dcx() .struct_span_err(path_span, "usage of deprecated attribute") diff --git a/src/tools/clippy/clippy_utils/src/qualify_min_const_fn.rs b/src/tools/clippy/clippy_utils/src/qualify_min_const_fn.rs index 50b7cd9bb5c8c..bd14554ef8b82 100644 --- a/src/tools/clippy/clippy_utils/src/qualify_min_const_fn.rs +++ b/src/tools/clippy/clippy_utils/src/qualify_min_const_fn.rs @@ -405,7 +405,7 @@ fn check_terminator<'tcx>( // within const fns. `transmute` is allowed in all other const contexts. // This won't really scale to more intrinsics or functions. Let's allow const // transmutes in const fn before we add more hacks to this. - if cx.tcx.is_intrinsic(fn_def_id, sym::transmute) { + if cx.tcx.is_rustc_intrinsic(fn_def_id, sym::transmute) { return Err(( span, "can only call `transmute` from const items, not `const fn`".into(), diff --git a/src/tools/miri/src/intrinsics/mod.rs b/src/tools/miri/src/intrinsics/mod.rs index 5b5104731ac0b..d6e0e24e8ab15 100644 --- a/src/tools/miri/src/intrinsics/mod.rs +++ b/src/tools/miri/src/intrinsics/mod.rs @@ -50,13 +50,13 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { if ecx.eval_intrinsic(instance, args, dest, ret)? { return interp_ok(None); } - let intrinsic_name = ecx.tcx.item_name(instance.def_id()); - let intrinsic_name = intrinsic_name.as_str(); + let intrinsic = ecx.tcx.intrinsic(instance.def_id()).unwrap(); + let intrinsic_name = &intrinsic.name.to_string(); let res = ecx.emulate_intrinsic_by_name(intrinsic_name, instance.args, args, dest, ret)?; res.jump_to_next_block(ecx, dest, ret, Some(unwind), |ecx| { // We haven't handled the intrinsic, let's see if we can use a fallback body. - if ecx.tcx.intrinsic(instance.def_id()).unwrap().must_be_overridden { + if intrinsic.must_be_overridden { throw_unsup_format!("unimplemented intrinsic: `{intrinsic_name}`") } let intrinsic_fallback_is_spec = ecx diff --git a/src/tools/miri/tests/pass/intrinsics/backend-fallback.rs b/src/tools/miri/tests/pass/intrinsics/backend-fallback.rs new file mode 100644 index 0000000000000..b3519833018c4 --- /dev/null +++ b/src/tools/miri/tests/pass/intrinsics/backend-fallback.rs @@ -0,0 +1,18 @@ +#![feature(intrinsics)] + +// Having a fallback body that does not match the +// intrinsic is not a good idea, but we do that here for testing. +// +// It's especially a bad idea to mark such a function as +// #[miri::intrinsic_fallback_is_spec]. +#[rustc_intrinsic(llvm = "llvm.fshl.i64")] +#[miri::intrinsic_fallback_is_spec] +fn not_quite_fshl(a: i64, b: i64, sh: i64) -> i64 { + eprintln!("{a} {b} {sh}"); + 0 +} + +fn main() { + let res = not_quite_fshl(1, 2, 3); + assert_eq!(res, 0); +} diff --git a/src/tools/miri/tests/pass/intrinsics/backend-fallback.stderr b/src/tools/miri/tests/pass/intrinsics/backend-fallback.stderr new file mode 100644 index 0000000000000..b85905ec0b994 --- /dev/null +++ b/src/tools/miri/tests/pass/intrinsics/backend-fallback.stderr @@ -0,0 +1 @@ +1 2 3 diff --git a/tests/run-make/incremental-extern-path/foo.rs b/tests/run-make/incremental-extern-path/foo.rs new file mode 100644 index 0000000000000..1aa26083937ac --- /dev/null +++ b/tests/run-make/incremental-extern-path/foo.rs @@ -0,0 +1,9 @@ +#![feature(no_core, rustc_attrs)] +#![no_core] +#![no_main] +#![rustc_partition_reused(module = "repro", cfg = "reuse")] + +extern crate minicore; + +#[unsafe(no_mangle)] +pub fn entry() {} diff --git a/tests/run-make/incremental-extern-path/rmake.rs b/tests/run-make/incremental-extern-path/rmake.rs new file mode 100644 index 0000000000000..4a37496a6b87e --- /dev/null +++ b/tests/run-make/incremental-extern-path/rmake.rs @@ -0,0 +1,36 @@ +// Test file compiling a program with incrementals under dir `a` then renaming to dir `b` and +// compiling again. Expects incremental reuse on the second invocation. +// +// Used to ensure incrementals aren't invalidated due to a dependency on the +// filesystem path. +//@ only-linux +//@ needs-backends: llvm + +use run_make_support::{rfs, rustc, rustc_minicore}; + +fn build(dir: &str, revision: &str) { + rustc() + .current_dir(dir) + .input("foo.rs") + .crate_name("repro") + .crate_type("bin") + .emit("obj") + .cfg(revision) + .extern_("minicore", "libminicore.rlib") + .incremental("incremental") + .debuginfo("2") + .arg("-Cpanic=abort") + .arg("-Zremap-cwd-prefix=.") + .arg("-Zquery-dep-graph") + .arg("-Zincremental-verify-ich") + .run(); +} + +fn main() { + rfs::create_dir("a"); + rustc_minicore().arg("-Cpanic=abort").output("a/libminicore.rlib").run(); + rfs::copy("foo.rs", "a/foo.rs"); + build("a", "cold"); + rfs::rename("a", "b"); + build("b", "reuse"); +} diff --git a/tests/rustdoc-ui/check-doc-alias-attr-location.rs b/tests/rustdoc-ui/check-doc-alias-attr-location.rs index 2b272b7066793..ac7d519a65c99 100644 --- a/tests/rustdoc-ui/check-doc-alias-attr-location.rs +++ b/tests/rustdoc-ui/check-doc-alias-attr-location.rs @@ -5,8 +5,10 @@ pub trait Foo { } // FIXME(#96009): Don't emit `unused_doc_comments` here, we already emit an error anyway. -//~v WARN -#[doc(alias = "foo")] //~ ERROR +#[doc(alias = "foo")] +//~^ ERROR `#[doc(alias = "...")]` isn't allowed on +//~| WARN cannot be used on +//~| WARN previously accepted extern "C" {} #[doc(alias = "bar")] //~ ERROR diff --git a/tests/rustdoc-ui/check-doc-alias-attr-location.stderr b/tests/rustdoc-ui/check-doc-alias-attr-location.stderr index ace40d4fe7c91..9f4d7a09d46ec 100644 --- a/tests/rustdoc-ui/check-doc-alias-attr-location.stderr +++ b/tests/rustdoc-ui/check-doc-alias-attr-location.stderr @@ -1,37 +1,38 @@ -warning: unused doc comment - --> $DIR/check-doc-alias-attr-location.rs:9:1 - | -LL | #[doc(alias = "foo")] - | ^^^^^^^^^^^^^^^^^^^^^ -LL | extern "C" {} - | ------------- rustdoc does not generate documentation for extern blocks - | - = help: use `//` for a plain comment - = note: `#[warn(unused_doc_comments)]` (part of `#[warn(unused)]`) on by default - error: `#[doc(alias = "...")]` isn't allowed on foreign module - --> $DIR/check-doc-alias-attr-location.rs:9:15 + --> $DIR/check-doc-alias-attr-location.rs:8:15 | LL | #[doc(alias = "foo")] | ^^^^^ error: `#[doc(alias = "...")]` isn't allowed on implementation block - --> $DIR/check-doc-alias-attr-location.rs:12:15 + --> $DIR/check-doc-alias-attr-location.rs:14:15 | LL | #[doc(alias = "bar")] | ^^^^^ error: `#[doc(alias = "...")]` isn't allowed on implementation block - --> $DIR/check-doc-alias-attr-location.rs:18:15 + --> $DIR/check-doc-alias-attr-location.rs:20:15 | LL | #[doc(alias = "foobar")] | ^^^^^^^^ error: `#[doc(alias = "...")]` isn't allowed on type alias in implementation block - --> $DIR/check-doc-alias-attr-location.rs:20:19 + --> $DIR/check-doc-alias-attr-location.rs:22:19 | LL | #[doc(alias = "assoc")] | ^^^^^^^ +warning: the `doc` attribute cannot be used on foreign modules + --> $DIR/check-doc-alias-attr-location.rs:8:3 + | +LL | #[doc(alias = "foo")] + | ^^^ +... +LL | extern "C" {} + | + = help: the `doc` attribute can be applied to associated consts, associated types, constants, crates, data types, enum variants, extern crates, foreign statics, functions, impl blocks, macro defs, modules, statics, struct fields, trait aliases, traits, type aliases, and use statements + = warning: this was previously accepted by the compiler but is being phased out; it will become a hard error in a future release! + = note: `#[warn(unused_doc_comments)]` (part of `#[warn(unused)]`) on by default + error: aborting due to 4 previous errors; 1 warning emitted diff --git a/tests/rustdoc-ui/lints/unused-doc-comments.stderr b/tests/rustdoc-ui/lints/unused-doc-comments.stderr index 65656ee78f717..dc74154e24005 100644 --- a/tests/rustdoc-ui/lints/unused-doc-comments.stderr +++ b/tests/rustdoc-ui/lints/unused-doc-comments.stderr @@ -2,24 +2,24 @@ warning: unused doc comment --> $DIR/unused-doc-comments.rs:10:1 | LL | /** */ m!(); - | ^^^^^^ rustdoc does not generate documentation for macro invocations + | ^^^^^^ rustdoc does not generate documentation for macro calls | - = help: to document an item produced by a macro, the macro must produce the documentation as part of its expansion + = help: use `/* */` for a plain comment = note: `#[warn(unused_doc_comments)]` (part of `#[warn(unused)]`) on by default warning: unused doc comment - --> $DIR/unused-doc-comments.rs:4:10 + --> $DIR/unused-doc-comments.rs:5:5 | -LL | pub fn f() { - | ^^^^^^- rustdoc does not generate documentation for generic parameters +LL | /** */ let (); + | ^^^^^^ rustdoc does not generate documentation for statements | = help: use `/* */` for a plain comment warning: unused doc comment - --> $DIR/unused-doc-comments.rs:5:5 + --> $DIR/unused-doc-comments.rs:4:10 | -LL | /** */ let (); - | ^^^^^^ ------- rustdoc does not generate documentation for statements +LL | pub fn f() { + | ^^^^^^ rustdoc does not generate documentation for type parameters | = help: use `/* */` for a plain comment diff --git a/tests/ui/async-await/async-closures/async-closure-output-mismatch-issue-161619.current.stderr b/tests/ui/async-await/async-closures/async-closure-output-mismatch-issue-161619.current.stderr new file mode 100644 index 0000000000000..62ee5193400c9 --- /dev/null +++ b/tests/ui/async-await/async-closures/async-closure-output-mismatch-issue-161619.current.stderr @@ -0,0 +1,21 @@ +error[E0308]: mismatched types + --> $DIR/async-closure-output-mismatch-issue-161619.rs:16:27 + | +LL | for_each(async |_| Ok(String::new())); + | -- ^^^^^^^^^^^^^ expected `()`, found `String` + | | + | arguments to this enum variant are incorrect + | +help: the type constructed contains `String` due to the type of the argument passed + --> $DIR/async-closure-output-mismatch-issue-161619.rs:16:24 + | +LL | for_each(async |_| Ok(String::new())); + | ^^^-------------^ + | | + | this argument influences the type of `Ok` +note: tuple variant defined here + --> $SRC_DIR/core/src/result.rs:LL:COL + +error: aborting due to 1 previous error + +For more information about this error, try `rustc --explain E0308`. diff --git a/tests/ui/async-await/async-closures/async-closure-output-mismatch-issue-161619.next.stderr b/tests/ui/async-await/async-closures/async-closure-output-mismatch-issue-161619.next.stderr new file mode 100644 index 0000000000000..62ee5193400c9 --- /dev/null +++ b/tests/ui/async-await/async-closures/async-closure-output-mismatch-issue-161619.next.stderr @@ -0,0 +1,21 @@ +error[E0308]: mismatched types + --> $DIR/async-closure-output-mismatch-issue-161619.rs:16:27 + | +LL | for_each(async |_| Ok(String::new())); + | -- ^^^^^^^^^^^^^ expected `()`, found `String` + | | + | arguments to this enum variant are incorrect + | +help: the type constructed contains `String` due to the type of the argument passed + --> $DIR/async-closure-output-mismatch-issue-161619.rs:16:24 + | +LL | for_each(async |_| Ok(String::new())); + | ^^^-------------^ + | | + | this argument influences the type of `Ok` +note: tuple variant defined here + --> $SRC_DIR/core/src/result.rs:LL:COL + +error: aborting due to 1 previous error + +For more information about this error, try `rustc --explain E0308`. diff --git a/tests/ui/async-await/async-closures/async-closure-output-mismatch-issue-161619.rs b/tests/ui/async-await/async-closures/async-closure-output-mismatch-issue-161619.rs new file mode 100644 index 0000000000000..aa26814ff5dbc --- /dev/null +++ b/tests/ui/async-await/async-closures/async-closure-output-mismatch-issue-161619.rs @@ -0,0 +1,18 @@ +//@ edition: 2024 +//@ revisions: current next +//@ ignore-compare-mode-next-solver (explicit revisions) +//@[next] compile-flags: -Znext-solver + +use std::future::Future; + +fn for_each(_: F) +where + F: FnMut(()) -> Fut, + Fut: Future>, +{ +} + +fn main() { + for_each(async |_| Ok(String::new())); + //~^ ERROR mismatched types +} diff --git a/tests/ui/attributes/attr-on-mac-call.rs b/tests/ui/attributes/attr-on-mac-call.rs index 28fbd0ca48600..da57853f4bddd 100644 --- a/tests/ui/attributes/attr-on-mac-call.rs +++ b/tests/ui/attributes/attr-on-mac-call.rs @@ -8,72 +8,95 @@ fn main() { #[export_name = "x"] //~^ WARN attribute cannot be used on macro calls //~| WARN previously accepted + unreachable!(); #[unsafe(naked)] //~^ WARN attribute cannot be used on macro calls //~| WARN previously accepted + unreachable!(); #[track_caller] //~^ WARN attribute cannot be used on macro calls //~| WARN previously accepted + unreachable!(); #[used] //~^ WARN attribute cannot be used on macro calls //~| WARN previously accepted + unreachable!(); #[target_feature(enable = "x")] //~^ WARN attribute cannot be used on macro calls //~| WARN previously accepted + unreachable!(); #[deprecated] //~^ WARN attribute cannot be used on macro calls //~| WARN previously accepted + unreachable!(); #[inline] //~^ WARN attribute cannot be used on macro calls //~| WARN previously accepted + unreachable!(); #[link_name = "x"] //~^ WARN attribute cannot be used on macro calls //~| WARN previously accepted + unreachable!(); #[link_section = "__TEXT,__text"] //~^ WARN attribute cannot be used on macro calls //~| WARN previously accepted + unreachable!(); #[link_ordinal(42)] //~^ WARN attribute cannot be used on macro calls //~| WARN previously accepted + unreachable!(); #[non_exhaustive] //~^ WARN attribute cannot be used on macro calls //~| WARN previously accepted + unreachable!(); #[proc_macro] //~^ WARN attribute cannot be used on macro calls //~| WARN previously accepted + unreachable!(); #[cold] //~^ WARN attribute cannot be used on macro calls //~| WARN previously accepted + unreachable!(); #[no_mangle] //~^ WARN attribute cannot be used on macro calls //~| WARN previously accepted + unreachable!(); #[deprecated] //~^ WARN attribute cannot be used on macro calls //~| WARN previously accepted + unreachable!(); #[automatically_derived] //~^ WARN attribute cannot be used on macro calls //~| WARN previously accepted + unreachable!(); #[macro_use] //~^ WARN attribute cannot be used on macro calls //~| WARN previously accepted + unreachable!(); #[must_use] //~^ WARN attribute cannot be used on macro calls //~| WARN previously accepted + unreachable!(); #[no_implicit_prelude] //~^ WARN attribute cannot be used on macro calls //~| WARN previously accepted + unreachable!(); #[path = ""] //~^ WARN attribute cannot be used on macro calls //~| WARN previously accepted + unreachable!(); #[ignore] //~^ WARN attribute cannot be used on macro calls //~| WARN previously accepted + unreachable!(); #[should_panic] //~^ WARN attribute cannot be used on macro calls //~| WARN previously accepted + unreachable!(); #[link_name = "x"] //~^ WARN attribute cannot be used on macro calls //~| WARN previously accepted + unreachable!(); #[sanitize(address = "off")] //~^ ERROR attribute cannot be used on macro calls unreachable!(); diff --git a/tests/ui/attributes/attr-on-mac-call.stderr b/tests/ui/attributes/attr-on-mac-call.stderr index 0d6fe64db735f..d51f3ef574688 100644 --- a/tests/ui/attributes/attr-on-mac-call.stderr +++ b/tests/ui/attributes/attr-on-mac-call.stderr @@ -1,5 +1,5 @@ error: the `sanitize` attribute cannot be used on macro calls - --> $DIR/attr-on-mac-call.rs:77:7 + --> $DIR/attr-on-mac-call.rs:100:7 | LL | #[sanitize(address = "off")] | ^^^^^^^^ @@ -10,7 +10,7 @@ LL | unreachable!(); = note: attributes on a macro invocation apply to the invocation itself and are not forwarded to its expansion error[E0658]: SIMD types are experimental and possibly buggy - --> $DIR/attr-on-mac-call.rs:106:12 + --> $DIR/attr-on-mac-call.rs:129:12 | LL | #[repr(simd)] | ^^^^ @@ -20,7 +20,7 @@ LL | #[repr(simd)] = note: this compiler was built on YYYY-MM-DD; consider upgrading it if it is out of date error: the `repr(simd)` attribute cannot be used on macro calls - --> $DIR/attr-on-mac-call.rs:106:7 + --> $DIR/attr-on-mac-call.rs:129:7 | LL | #[repr(simd)] | ^^^^^^^^^^ @@ -31,31 +31,31 @@ LL | unreachable!(); = note: attributes on a macro invocation apply to the invocation itself and are not forwarded to its expansion error: crate-level attribute should be an inner attribute: add an exclamation mark: `#![register_tool]` - --> $DIR/attr-on-mac-call.rs:110:5 + --> $DIR/attr-on-mac-call.rs:133:5 | LL | #[register_tool(xyz)] | ^^^^^^^^^^^^^^^^^^^^^ | note: this attribute does not have an `!`, which means it is applied to this macro call - --> $DIR/attr-on-mac-call.rs:112:5 + --> $DIR/attr-on-mac-call.rs:135:5 | LL | unreachable!(); | ^^^^^^^^^^^^^^ error: attribute value must be a literal - --> $DIR/attr-on-mac-call.rs:113:20 + --> $DIR/attr-on-mac-call.rs:136:20 | LL | #[deprecated = concat!("woah", "dude")] | ^^^^^^^^^^^^^^^^^^^^^^^ error: attribute value must be a literal - --> $DIR/attr-on-mac-call.rs:115:13 + --> $DIR/attr-on-mac-call.rs:138:13 | LL | #[doc = concat!("woah", "dude")] | ^^^^^^^^^^^^^^^^^^^^^^^ error: attribute value must be a literal - --> $DIR/attr-on-mac-call.rs:118:13 + --> $DIR/attr-on-mac-call.rs:141:13 | LL | #[doc = { | _____________^ @@ -67,7 +67,7 @@ LL | | }] | |_____^ error: attribute value must be a literal - --> $DIR/attr-on-mac-call.rs:126:13 + --> $DIR/attr-on-mac-call.rs:149:13 | LL | #[doc = { | _____________^ @@ -93,7 +93,7 @@ LL | #![warn(unused_attributes)] | ^^^^^^^^^^^^^^^^^ warning: the `naked` attribute cannot be used on macro calls - --> $DIR/attr-on-mac-call.rs:11:14 + --> $DIR/attr-on-mac-call.rs:12:14 | LL | #[unsafe(naked)] | ^^^^^ @@ -105,7 +105,7 @@ LL | unreachable!(); = note: attributes on a macro invocation apply to the invocation itself and are not forwarded to its expansion warning: the `track_caller` attribute cannot be used on macro calls - --> $DIR/attr-on-mac-call.rs:14:7 + --> $DIR/attr-on-mac-call.rs:16:7 | LL | #[track_caller] | ^^^^^^^^^^^^ @@ -117,7 +117,7 @@ LL | unreachable!(); = note: attributes on a macro invocation apply to the invocation itself and are not forwarded to its expansion warning: the `used` attribute cannot be used on macro calls - --> $DIR/attr-on-mac-call.rs:17:7 + --> $DIR/attr-on-mac-call.rs:20:7 | LL | #[used] | ^^^^ @@ -129,7 +129,7 @@ LL | unreachable!(); = note: attributes on a macro invocation apply to the invocation itself and are not forwarded to its expansion warning: the `target_feature` attribute cannot be used on macro calls - --> $DIR/attr-on-mac-call.rs:20:7 + --> $DIR/attr-on-mac-call.rs:24:7 | LL | #[target_feature(enable = "x")] | ^^^^^^^^^^^^^^ @@ -141,7 +141,7 @@ LL | unreachable!(); = note: attributes on a macro invocation apply to the invocation itself and are not forwarded to its expansion warning: the `deprecated` attribute cannot be used on macro calls - --> $DIR/attr-on-mac-call.rs:23:7 + --> $DIR/attr-on-mac-call.rs:28:7 | LL | #[deprecated] | ^^^^^^^^^^ @@ -153,7 +153,7 @@ LL | unreachable!(); = note: attributes on a macro invocation apply to the invocation itself and are not forwarded to its expansion warning: the `inline` attribute cannot be used on macro calls - --> $DIR/attr-on-mac-call.rs:26:7 + --> $DIR/attr-on-mac-call.rs:32:7 | LL | #[inline] | ^^^^^^ @@ -165,7 +165,7 @@ LL | unreachable!(); = note: attributes on a macro invocation apply to the invocation itself and are not forwarded to its expansion warning: the `link_name` attribute cannot be used on macro calls - --> $DIR/attr-on-mac-call.rs:29:7 + --> $DIR/attr-on-mac-call.rs:36:7 | LL | #[link_name = "x"] | ^^^^^^^^^ @@ -177,7 +177,7 @@ LL | unreachable!(); = note: attributes on a macro invocation apply to the invocation itself and are not forwarded to its expansion warning: the `link_section` attribute cannot be used on macro calls - --> $DIR/attr-on-mac-call.rs:32:7 + --> $DIR/attr-on-mac-call.rs:40:7 | LL | #[link_section = "__TEXT,__text"] | ^^^^^^^^^^^^ @@ -189,7 +189,7 @@ LL | unreachable!(); = note: attributes on a macro invocation apply to the invocation itself and are not forwarded to its expansion warning: the `link_ordinal` attribute cannot be used on macro calls - --> $DIR/attr-on-mac-call.rs:35:7 + --> $DIR/attr-on-mac-call.rs:44:7 | LL | #[link_ordinal(42)] | ^^^^^^^^^^^^ @@ -201,7 +201,7 @@ LL | unreachable!(); = note: attributes on a macro invocation apply to the invocation itself and are not forwarded to its expansion warning: the `non_exhaustive` attribute cannot be used on macro calls - --> $DIR/attr-on-mac-call.rs:38:7 + --> $DIR/attr-on-mac-call.rs:48:7 | LL | #[non_exhaustive] | ^^^^^^^^^^^^^^ @@ -213,7 +213,7 @@ LL | unreachable!(); = note: attributes on a macro invocation apply to the invocation itself and are not forwarded to its expansion warning: the `proc_macro` attribute cannot be used on macro calls - --> $DIR/attr-on-mac-call.rs:41:7 + --> $DIR/attr-on-mac-call.rs:52:7 | LL | #[proc_macro] | ^^^^^^^^^^ @@ -225,7 +225,7 @@ LL | unreachable!(); = note: attributes on a macro invocation apply to the invocation itself and are not forwarded to its expansion warning: the `cold` attribute cannot be used on macro calls - --> $DIR/attr-on-mac-call.rs:44:7 + --> $DIR/attr-on-mac-call.rs:56:7 | LL | #[cold] | ^^^^ @@ -237,7 +237,7 @@ LL | unreachable!(); = note: attributes on a macro invocation apply to the invocation itself and are not forwarded to its expansion warning: the `no_mangle` attribute cannot be used on macro calls - --> $DIR/attr-on-mac-call.rs:47:7 + --> $DIR/attr-on-mac-call.rs:60:7 | LL | #[no_mangle] | ^^^^^^^^^ @@ -249,7 +249,7 @@ LL | unreachable!(); = note: attributes on a macro invocation apply to the invocation itself and are not forwarded to its expansion warning: the `deprecated` attribute cannot be used on macro calls - --> $DIR/attr-on-mac-call.rs:50:7 + --> $DIR/attr-on-mac-call.rs:64:7 | LL | #[deprecated] | ^^^^^^^^^^ @@ -261,7 +261,7 @@ LL | unreachable!(); = note: attributes on a macro invocation apply to the invocation itself and are not forwarded to its expansion warning: the `automatically_derived` attribute cannot be used on macro calls - --> $DIR/attr-on-mac-call.rs:53:7 + --> $DIR/attr-on-mac-call.rs:68:7 | LL | #[automatically_derived] | ^^^^^^^^^^^^^^^^^^^^^ @@ -273,7 +273,7 @@ LL | unreachable!(); = note: attributes on a macro invocation apply to the invocation itself and are not forwarded to its expansion warning: the `macro_use` attribute cannot be used on macro calls - --> $DIR/attr-on-mac-call.rs:56:7 + --> $DIR/attr-on-mac-call.rs:72:7 | LL | #[macro_use] | ^^^^^^^^^ @@ -285,7 +285,7 @@ LL | unreachable!(); = note: attributes on a macro invocation apply to the invocation itself and are not forwarded to its expansion warning: the `must_use` attribute cannot be used on macro calls - --> $DIR/attr-on-mac-call.rs:59:7 + --> $DIR/attr-on-mac-call.rs:76:7 | LL | #[must_use] | ^^^^^^^^ @@ -297,7 +297,7 @@ LL | unreachable!(); = note: attributes on a macro invocation apply to the invocation itself and are not forwarded to its expansion warning: the `no_implicit_prelude` attribute cannot be used on macro calls - --> $DIR/attr-on-mac-call.rs:62:7 + --> $DIR/attr-on-mac-call.rs:80:7 | LL | #[no_implicit_prelude] | ^^^^^^^^^^^^^^^^^^^ @@ -309,7 +309,7 @@ LL | unreachable!(); = note: attributes on a macro invocation apply to the invocation itself and are not forwarded to its expansion warning: the `path` attribute cannot be used on macro calls - --> $DIR/attr-on-mac-call.rs:65:7 + --> $DIR/attr-on-mac-call.rs:84:7 | LL | #[path = ""] | ^^^^ @@ -321,7 +321,7 @@ LL | unreachable!(); = note: attributes on a macro invocation apply to the invocation itself and are not forwarded to its expansion warning: the `ignore` attribute cannot be used on macro calls - --> $DIR/attr-on-mac-call.rs:68:7 + --> $DIR/attr-on-mac-call.rs:88:7 | LL | #[ignore] | ^^^^^^ @@ -333,7 +333,7 @@ LL | unreachable!(); = note: attributes on a macro invocation apply to the invocation itself and are not forwarded to its expansion warning: the `should_panic` attribute cannot be used on macro calls - --> $DIR/attr-on-mac-call.rs:71:7 + --> $DIR/attr-on-mac-call.rs:92:7 | LL | #[should_panic] | ^^^^^^^^^^^^ @@ -345,7 +345,7 @@ LL | unreachable!(); = note: attributes on a macro invocation apply to the invocation itself and are not forwarded to its expansion warning: the `link_name` attribute cannot be used on macro calls - --> $DIR/attr-on-mac-call.rs:74:7 + --> $DIR/attr-on-mac-call.rs:96:7 | LL | #[link_name = "x"] | ^^^^^^^^^ @@ -357,7 +357,7 @@ LL | unreachable!(); = note: attributes on a macro invocation apply to the invocation itself and are not forwarded to its expansion warning: the `repr()` attribute cannot be used on macro calls - --> $DIR/attr-on-mac-call.rs:81:7 + --> $DIR/attr-on-mac-call.rs:104:7 | LL | #[repr()] | ^^^^^^ @@ -369,7 +369,7 @@ LL | unreachable!(); = note: attributes on a macro invocation apply to the invocation itself and are not forwarded to its expansion warning: unused attribute - --> $DIR/attr-on-mac-call.rs:81:5 + --> $DIR/attr-on-mac-call.rs:104:5 | LL | #[repr()] | ^^^^^^^^^ help: remove this attribute @@ -377,7 +377,7 @@ LL | #[repr()] = note: using `repr` with an empty list has no effect warning: the `repr(u8)` attribute cannot be used on macro calls - --> $DIR/attr-on-mac-call.rs:86:7 + --> $DIR/attr-on-mac-call.rs:109:7 | LL | #[repr(u8)] | ^^^^^^^^ @@ -389,7 +389,7 @@ LL | unreachable!(); = note: attributes on a macro invocation apply to the invocation itself and are not forwarded to its expansion warning: the `repr(align(...))` attribute cannot be used on macro calls - --> $DIR/attr-on-mac-call.rs:90:7 + --> $DIR/attr-on-mac-call.rs:113:7 | LL | #[repr(align(8))] | ^^^^^^^^^^^^^^ @@ -401,7 +401,7 @@ LL | unreachable!(); = note: attributes on a macro invocation apply to the invocation itself and are not forwarded to its expansion warning: the `repr(packed)` attribute cannot be used on macro calls - --> $DIR/attr-on-mac-call.rs:94:7 + --> $DIR/attr-on-mac-call.rs:117:7 | LL | #[repr(packed)] | ^^^^^^^^^^^^ @@ -413,7 +413,7 @@ LL | unreachable!(); = note: attributes on a macro invocation apply to the invocation itself and are not forwarded to its expansion warning: the `repr(C)` attribute cannot be used on macro calls - --> $DIR/attr-on-mac-call.rs:98:7 + --> $DIR/attr-on-mac-call.rs:121:7 | LL | #[repr(C)] | ^^^^^^^ @@ -425,7 +425,7 @@ LL | unreachable!(); = note: attributes on a macro invocation apply to the invocation itself and are not forwarded to its expansion warning: the `repr(Rust)` attribute cannot be used on macro calls - --> $DIR/attr-on-mac-call.rs:102:7 + --> $DIR/attr-on-mac-call.rs:125:7 | LL | #[repr(Rust)] | ^^^^^^^^^^ diff --git a/tests/ui/attributes/show_spans_generic_args.rs b/tests/ui/attributes/show_spans_generic_args.rs new file mode 100644 index 0000000000000..d7475803a0b49 --- /dev/null +++ b/tests/ui/attributes/show_spans_generic_args.rs @@ -0,0 +1,36 @@ +// Illustrates the behavior of the `rustc_show_spans` internal attribute +// on generic arguments. + +//@ check-pass +#![feature(rustc_attrs)] + +#[rustc_show_spans(generic_args)] +fn angle_bracketed() { + let _: Vec; + let _: Vec>; + let _ = Vec::::new(); +} + +macro_rules! parenthesized { + ($f:ident) => { + let _: &dyn $f(u8) -> u8; + }; +} + +#[rustc_show_spans(generic_args)] +fn parenthesized_from_ident() { + parenthesized!(Fn); +} + +macro_rules! arrow { + ($f:tt $args:tt, $o:tt) => { + let _: &dyn $f $args -> $o; + }; +} + +#[rustc_show_spans(path)] +fn arrow_from_macro() { + arrow!(Fn (u8), u8); +} + +fn main() {} diff --git a/tests/ui/attributes/show_spans_generic_args.stderr b/tests/ui/attributes/show_spans_generic_args.stderr new file mode 100644 index 0000000000000..61186bf4b2298 --- /dev/null +++ b/tests/ui/attributes/show_spans_generic_args.stderr @@ -0,0 +1,58 @@ +note: showing the spans of the generic_args + --> $DIR/show_spans_generic_args.rs:9:15 + | +LL | let _: Vec; + | ^^^^ + +note: showing the spans of the generic_args + --> $DIR/show_spans_generic_args.rs:10:15 + | +LL | let _: Vec>; + | ^^^^^^^^^^^^ + +note: showing the spans of the generic_args + --> $DIR/show_spans_generic_args.rs:10:22 + | +LL | let _: Vec>; + | ^^^^ + +note: showing the spans of the generic_args + --> $DIR/show_spans_generic_args.rs:11:18 + | +LL | let _ = Vec::::new(); + | ^^^^ + +note: showing the spans of the generic_args + --> $DIR/show_spans_generic_args.rs:16:23 + | +LL | macro_rules! parenthesized { +LL | ($f:ident) => { +LL | let _: &dyn $f(u8) -> u8; + | ^^^^^^^^^^ +... +LL | parenthesized!(Fn); + | ------------------ in this macro invocation + +note: showing the spans of the path + --> $DIR/show_spans_generic_args.rs:27:21 + | +LL | macro_rules! arrow { +LL | ($f:tt $args:tt, $o:tt) => { +LL | let _: &dyn $f $args -> $o; + | ^^^^^^^^^^^^^^ +... +LL | arrow!(Fn (u8), u8); + | ------------------- in this macro invocation + +note: showing the spans of the path + --> $DIR/show_spans_generic_args.rs:33:16 + | +LL | arrow!(Fn (u8), u8); + | ^^ + +note: showing the spans of the path + --> $DIR/show_spans_generic_args.rs:33:21 + | +LL | arrow!(Fn (u8), u8); + | ^^ + diff --git a/tests/ui/consts/auxiliary/unstable_intrinsic.rs b/tests/ui/consts/auxiliary/unstable_intrinsic.rs index c1c7571e0c90c..a270d6873d805 100644 --- a/tests/ui/consts/auxiliary/unstable_intrinsic.rs +++ b/tests/ui/consts/auxiliary/unstable_intrinsic.rs @@ -1,11 +1,20 @@ #![feature(staged_api, rustc_attrs, intrinsics)] -#![stable(since="1.0.0", feature = "stable")] +#![stable(since = "1.0.0", feature = "stable")] #[unstable(feature = "unstable", issue = "42")] #[rustc_intrinsic] pub const unsafe fn size_of_val(x: *const T) -> usize; +#[unstable(feature = "unstable", issue = "42")] +#[rustc_intrinsic(llvm = "llvm.fshl.i64")] +pub const unsafe fn llvm_fshl(a: i64, b: i64, sh: i64) -> i64; + #[unstable(feature = "unstable", issue = "42")] #[rustc_const_unstable(feature = "unstable", issue = "42")] #[rustc_intrinsic] pub const unsafe fn align_of_val(x: *const T) -> usize; + +#[unstable(feature = "unstable", issue = "42")] +#[rustc_const_unstable(feature = "unstable", issue = "42")] +#[rustc_intrinsic(llvm = "llvm.fshl.i64")] +pub const unsafe fn llvm_fshl2(a: i64, b: i64, sh: i64) -> i64; diff --git a/tests/ui/consts/const-unstable-intrinsic.rs b/tests/ui/consts/const-unstable-intrinsic.rs index edb6d365da441..1fcc0b2479c9a 100644 --- a/tests/ui/consts/const-unstable-intrinsic.rs +++ b/tests/ui/consts/const-unstable-intrinsic.rs @@ -26,17 +26,39 @@ const fn const_main() { align_of_val(&x); //~^ERROR: cannot use `#[feature(local)]` } + unsafe { + unstable_intrinsic::llvm_fshl(0, 0, 0); + //~^ERROR: unstable library feature `unstable` + //~|ERROR: not yet stable as a const intrinsic + unstable_intrinsic::llvm_fshl2(0, 0, 0); + //~^ERROR: unstable library feature `unstable` + //~|ERROR: not yet stable as a const intrinsic + + llvm_fshl(0, 0, 0); + //~^ERROR: cannot use `#[feature(local)]` + llvm_fshl2(0, 0, 0); + //~^ERROR: cannot use `#[feature(local)]` + } } #[unstable(feature = "local", issue = "42")] #[rustc_intrinsic] pub const unsafe fn size_of_val(x: *const T) -> usize; +#[unstable(feature = "local", issue = "42")] +#[rustc_intrinsic(llvm = "llvm.fshl.i64")] +pub const unsafe fn llvm_fshl(a: i64, b: i64, sh: i64) -> i64; + #[unstable(feature = "local", issue = "42")] #[rustc_const_unstable(feature = "local", issue = "42")] #[rustc_intrinsic] pub const unsafe fn align_of_val(x: *const T) -> usize; +#[unstable(feature = "local", issue = "42")] +#[rustc_const_unstable(feature = "local", issue = "42")] +#[rustc_intrinsic(llvm = "llvm.fshl.i64")] +pub const unsafe fn llvm_fshl2(a: i64, b: i64, sh: i64) -> i64; + #[stable(feature = "rust1", since = "1.0.0")] #[rustc_const_stable(feature = "const_intrinsic_copy", since = "1.63.0")] pub const unsafe fn copy(src: *const T, dst: *mut T, count: usize) { @@ -56,6 +78,12 @@ mod fallback { //~^ ERROR cannot use `#[feature(local)]` } + #[rustc_intrinsic(llvm = "llvm.fshl.i64")] + const unsafe fn llvm_fshl(a: i64, b: i64, sh: i64) -> i64 { + super::llvm_fshl(a, b, sh) + //~^ ERROR cannot use `#[feature(local)]` + } + // Even unstable intrinsics must be const-checked if we add // `rustc_intrinsic_const_stable_indirect`. #[rustc_intrinsic] @@ -65,6 +93,14 @@ mod fallback { super::align_of_val(x) //~^ ERROR cannot use `#[feature(local)]` } + + #[rustc_intrinsic(llvm = "llvm.fshl.i64")] + #[rustc_const_unstable(feature = "core_intrinsics", issue = "none")] + #[rustc_intrinsic_const_stable_indirect] + pub const unsafe fn llvm_fshl2(a: i64, b: i64, sh: i64) -> i64 { + super::llvm_fshl2(a, b, sh) + //~^ ERROR cannot use `#[feature(local)]` + } } // `rustc_const_stable_indirect` does not actually make this intrinsic callable diff --git a/tests/ui/consts/const-unstable-intrinsic.stderr b/tests/ui/consts/const-unstable-intrinsic.stderr index 4ef39d61cf801..5fbe3d89e9c13 100644 --- a/tests/ui/consts/const-unstable-intrinsic.stderr +++ b/tests/ui/consts/const-unstable-intrinsic.stderr @@ -18,6 +18,26 @@ LL | unstable_intrinsic::align_of_val(&x); = help: add `#![feature(unstable)]` 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]: use of unstable library feature `unstable` + --> $DIR/const-unstable-intrinsic.rs:30:9 + | +LL | unstable_intrinsic::llvm_fshl(0, 0, 0); + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + | + = note: see issue #42 for more information + = help: add `#![feature(unstable)]` 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]: use of unstable library feature `unstable` + --> $DIR/const-unstable-intrinsic.rs:33:9 + | +LL | unstable_intrinsic::llvm_fshl2(0, 0, 0); + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + | + = note: see issue #42 for more information + = help: add `#![feature(unstable)]` 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: `size_of_val` is not yet stable as a const intrinsic --> $DIR/const-unstable-intrinsic.rs:17:9 | @@ -64,8 +84,54 @@ LL + #[rustc_const_unstable(feature = "...", issue = "...")] LL | const fn const_main() { | +error: `llvm.fshl.i64` is not yet stable as a const intrinsic + --> $DIR/const-unstable-intrinsic.rs:30:9 + | +LL | unstable_intrinsic::llvm_fshl(0, 0, 0); + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + | +help: add `#![feature(unstable)]` to the crate attributes to enable + | +LL + #![feature(unstable)] + | + +error: `llvm.fshl.i64` is not yet stable as a const intrinsic + --> $DIR/const-unstable-intrinsic.rs:33:9 + | +LL | unstable_intrinsic::llvm_fshl2(0, 0, 0); + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + | +help: add `#![feature(unstable)]` to the crate attributes to enable + | +LL + #![feature(unstable)] + | + +error: const function that might be (indirectly) exposed to stable cannot use `#[feature(local)]` + --> $DIR/const-unstable-intrinsic.rs:37:9 + | +LL | llvm_fshl(0, 0, 0); + | ^^^^^^^^^^^^^^^^^^ + | +help: if the function is not (yet) meant to be exposed to stable const contexts, add `#[rustc_const_unstable]` + | +LL + #[rustc_const_unstable(feature = "...", issue = "...")] +LL | const fn const_main() { + | + +error: const function that might be (indirectly) exposed to stable cannot use `#[feature(local)]` + --> $DIR/const-unstable-intrinsic.rs:39:9 + | +LL | llvm_fshl2(0, 0, 0); + | ^^^^^^^^^^^^^^^^^^^ + | +help: if the function is not (yet) meant to be exposed to stable const contexts, add `#[rustc_const_unstable]` + | +LL + #[rustc_const_unstable(feature = "...", issue = "...")] +LL | const fn const_main() { + | + error: intrinsic `copy::copy` cannot be (indirectly) exposed to stable - --> $DIR/const-unstable-intrinsic.rs:47:14 + --> $DIR/const-unstable-intrinsic.rs:69:14 | LL | unsafe { copy(src, dst, count) } | ^^^^^^^^^^^^^^^^^^^^^ @@ -73,7 +139,7 @@ LL | unsafe { copy(src, dst, count) } = help: mark the caller as `#[rustc_const_unstable]`, or mark the intrinsic `#[rustc_intrinsic_const_stable_indirect]` (but this requires team approval) error: const function that might be (indirectly) exposed to stable cannot use `#[feature(local)]` - --> $DIR/const-unstable-intrinsic.rs:55:9 + --> $DIR/const-unstable-intrinsic.rs:77:9 | LL | super::size_of_val(src); | ^^^^^^^^^^^^^^^^^^^^^^^ @@ -85,19 +151,37 @@ LL | const unsafe fn copy(src: *const T, _dst: *mut T, _count: usize) { | error: const function that might be (indirectly) exposed to stable cannot use `#[feature(local)]` - --> $DIR/const-unstable-intrinsic.rs:65:9 + --> $DIR/const-unstable-intrinsic.rs:83:9 + | +LL | super::llvm_fshl(a, b, sh) + | ^^^^^^^^^^^^^^^^^^^^^^^^^^ + | +help: if the function is not (yet) meant to be exposed to stable const contexts, add `#[rustc_const_unstable]` + | +LL + #[rustc_const_unstable(feature = "...", issue = "...")] +LL | const unsafe fn llvm_fshl(a: i64, b: i64, sh: i64) -> i64 { + | + +error: const function that might be (indirectly) exposed to stable cannot use `#[feature(local)]` + --> $DIR/const-unstable-intrinsic.rs:93:9 | LL | super::align_of_val(x) | ^^^^^^^^^^^^^^^^^^^^^^ +error: const function that might be (indirectly) exposed to stable cannot use `#[feature(local)]` + --> $DIR/const-unstable-intrinsic.rs:101:9 + | +LL | super::llvm_fshl2(a, b, sh) + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^ + error: intrinsic `non_const_fallback::size_of_val` cannot be (indirectly) exposed to stable - --> $DIR/const-unstable-intrinsic.rs:84:18 + --> $DIR/const-unstable-intrinsic.rs:120:18 | LL | unsafe { size_of_val(x) } | ^^^^^^^^^^^^^^ | = help: mark the caller as `#[rustc_const_unstable]`, or mark the intrinsic `#[rustc_intrinsic_const_stable_indirect]` (but this requires team approval) -error: aborting due to 10 previous errors +error: aborting due to 18 previous errors For more information about this error, try `rustc --explain E0658`. diff --git a/tests/ui/generic-associated-types/gat-trait-path-parenthesised-args.stderr b/tests/ui/generic-associated-types/gat-trait-path-parenthesised-args.stderr index ee625dc4c79f5..7d15b6e6c3017 100644 --- a/tests/ui/generic-associated-types/gat-trait-path-parenthesised-args.stderr +++ b/tests/ui/generic-associated-types/gat-trait-path-parenthesised-args.stderr @@ -10,10 +10,10 @@ LL | fn foo<'a>(arg: Box>) {} | +++++++++++++ error: parenthesized generic arguments cannot be used in associated type constraints - --> $DIR/gat-trait-path-parenthesised-args.rs:6:27 + --> $DIR/gat-trait-path-parenthesised-args.rs:6:28 | LL | fn foo<'a>(arg: Box>) {} - | ^^^^^ + | ^^^^ | help: use angle brackets instead | @@ -22,12 +22,10 @@ LL + fn foo<'a>(arg: Box = &'a ()>>) {} | error: parenthesized generic arguments cannot be used in associated type constraints - --> $DIR/gat-trait-path-parenthesised-args.rs:13:27 + --> $DIR/gat-trait-path-parenthesised-args.rs:13:28 | LL | fn bar<'a>(arg: Box>) {} - | ^-- - | | - | help: remove these parentheses + | ^^ help: remove these parentheses error[E0107]: associated type takes 1 lifetime argument but 0 lifetime arguments were supplied --> $DIR/gat-trait-path-parenthesised-args.rs:6:27 diff --git a/tests/ui/intrinsics/rustc-llvm-intrinsic.rs b/tests/ui/intrinsics/rustc-llvm-intrinsic.rs new file mode 100644 index 0000000000000..261416019f3e0 --- /dev/null +++ b/tests/ui/intrinsics/rustc-llvm-intrinsic.rs @@ -0,0 +1,54 @@ +//@ run-pass +//@ revisions: backend_with_support backend_without_support force_fallback +//@ [backend_with_support]needs-backends: llvm +//@ [backend_without_support]ignore-backends: llvm +//@ [force_fallback]compile-flags: -Zforce-intrinsic-fallback + +#![feature(intrinsics)] + +// Having a fallback body that does not match the +// intrinsic is not a good idea, but we do that here for testing. +#[rustc_intrinsic(llvm = "llvm.fshl.i64")] +const fn sometimes_fshl(a: i64, b: i64, sh: i64) -> i64 { + a + b + sh +} + +#[cfg(backend_with_support)] +#[rustc_intrinsic(llvm = "llvm.fshl.i64")] +fn fshl_no_fallback(a: i64, b: i64, sh: i64) -> i64; + +// Test a built-in intrinsic name to make sure no +// implementation gets confused. +#[rustc_intrinsic(llvm = "llvm.fshl.i64")] +const fn size_of_val(a: i64, b: i64, sh: i64) -> i64 { + (((((a as i128) << 64) | (b as i128)) << sh) >> 64) as i64 +} + +#[cfg(backend_with_support)] +const IS_INTRINSIC: bool = true; + +#[cfg(any(backend_without_support, force_fallback))] +const IS_INTRINSIC: bool = false; + +fn main() { + let res = sometimes_fshl(1, 2, 3); + if IS_INTRINSIC { + assert_eq!(res, 8); + } else { + assert_eq!(res, 6); + } + + // Const eval should always use the fallback body, regardless + // of -Zforce-intrinsic-fallback. + let const_res = const { sometimes_fshl(1, 2, 3) }; + assert_eq!(const_res, 6); + + #[cfg(backend_with_support)] + { + let res = fshl_no_fallback(1, 2, 3); + assert_eq!(res, 8); + } + + assert_eq!(const { size_of_val(1, 2, 3) }, 8); + assert_eq!(size_of_val(1, 2, 3), 8); +} diff --git a/tests/ui/lint/unused/unused-doc-comments-edge-cases.stderr b/tests/ui/lint/unused/unused-doc-comments-edge-cases.stderr index 0f0288c6def60..c390238d61bd9 100644 --- a/tests/ui/lint/unused/unused-doc-comments-edge-cases.stderr +++ b/tests/ui/lint/unused/unused-doc-comments-edge-cases.stderr @@ -19,10 +19,9 @@ error: unused doc comment --> $DIR/unused-doc-comments-edge-cases.rs:6:9 | LL | /// useless doc comment - | ^^^^^^^^^^^^^^^^^^^^^^^ + | ^^^^^^^^^^^^^^^^^^^^^^^ rustdoc does not generate documentation for match arms LL | LL | _ => false, - | ---------- rustdoc does not generate documentation for match arms | = help: use `//` for a plain comment note: the lint level is defined here @@ -35,10 +34,9 @@ error: unused doc comment --> $DIR/unused-doc-comments-edge-cases.rs:23:5 | LL | /// useless doc comment - | ^^^^^^^^^^^^^^^^^^^^^^^ + | ^^^^^^^^^^^^^^^^^^^^^^^ rustdoc does not generate documentation for expressions ... LL | num == 3 - | --- rustdoc does not generate documentation for expressions | = help: use `//` for a plain comment @@ -46,10 +44,9 @@ error: unused doc comment --> $DIR/unused-doc-comments-edge-cases.rs:33:9 | LL | /// useless doc comment - | ^^^^^^^^^^^^^^^^^^^^^^^ + | ^^^^^^^^^^^^^^^^^^^^^^^ rustdoc does not generate documentation for struct fields LL | LL | foo: 3 - | ------ rustdoc does not generate documentation for expression fields | = help: use `//` for a plain comment @@ -57,10 +54,9 @@ error: unused doc comment --> $DIR/unused-doc-comments-edge-cases.rs:45:9 | LL | /// useless doc comment - | ^^^^^^^^^^^^^^^^^^^^^^^ + | ^^^^^^^^^^^^^^^^^^^^^^^ rustdoc does not generate documentation for pattern fields LL | LL | foo - | --- rustdoc does not generate documentation for pattern fields | = help: use `//` for a plain comment @@ -68,33 +64,27 @@ error: unused doc comment --> $DIR/unused-doc-comments-edge-cases.rs:55:27 | LL | fn doc_comment_on_generic<#[doc = "x"] T>(val: T) {} - | ^^^^^^^^^^^^ - rustdoc does not generate documentation for generic parameters + | ^^^^^^^^^^^^ rustdoc does not generate documentation for type parameters | = help: use `//` for a plain comment error: unused doc comment --> $DIR/unused-doc-comments-edge-cases.rs:59:5 | -LL | /// unused doc comment - | ^^^^^^^^^^^^^^^^^^^^^^ +LL | /// unused doc comment + | ^^^^^^^^^^^^^^^^^^^^^^ rustdoc does not generate documentation for expressions LL | -LL | / { -LL | | let x = 12; -LL | | } - | |_____- rustdoc does not generate documentation for expressions +LL | { | = help: use `//` for a plain comment error: unused doc comment --> $DIR/unused-doc-comments-edge-cases.rs:66:1 | -LL | /// unused doc comment - | ^^^^^^^^^^^^^^^^^^^^^^ +LL | /// unused doc comment + | ^^^^^^^^^^^^^^^^^^^^^^ rustdoc does not generate documentation for foreign modules LL | -LL | / extern "C" { -LL | | fn foo(); -LL | | } - | |_- rustdoc does not generate documentation for extern blocks +LL | extern "C" { | = help: use `//` for a plain comment diff --git a/tests/ui/lint/unused/unused-doc-comments-for-macros.rs b/tests/ui/lint/unused/unused-doc-comments-for-macros.rs index 8a3dd45c02115..ebe313baada87 100644 --- a/tests/ui/lint/unused/unused-doc-comments-for-macros.rs +++ b/tests/ui/lint/unused/unused-doc-comments-for-macros.rs @@ -15,14 +15,12 @@ fn main() { /// line3 foo!(); - // Even invalid doc attributes should emit the warning. #[doc = { let a = 1; let b = 1; let sum = a + b; assert_eq!(sum, 2); }] - //~^^^^^^ ERROR: unused doc comment - //~| ERROR attribute value must be a literal + //~^^^^^^ ERROR attribute value must be a literal foo!(); } diff --git a/tests/ui/lint/unused/unused-doc-comments-for-macros.stderr b/tests/ui/lint/unused/unused-doc-comments-for-macros.stderr index 9bb89974f9e23..88972c8196eab 100644 --- a/tests/ui/lint/unused/unused-doc-comments-for-macros.stderr +++ b/tests/ui/lint/unused/unused-doc-comments-for-macros.stderr @@ -1,5 +1,5 @@ error: attribute value must be a literal - --> $DIR/unused-doc-comments-for-macros.rs:19:13 + --> $DIR/unused-doc-comments-for-macros.rs:18:13 | LL | #[doc = { | _____________^ @@ -13,14 +13,12 @@ LL | | }] error: unused doc comment --> $DIR/unused-doc-comments-for-macros.rs:7:5 | -LL | / /// line1 -LL | | /// line2 -LL | | /// line3 - | |_____--------^ - | | - | rustdoc does not generate documentation for macro invocations +LL | /// line1 + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ rustdoc does not generate documentation for macro calls +... +LL | foo!(); | - = help: to document an item produced by a macro, the macro must produce the documentation as part of its expansion + = help: use `//` for a plain comment note: the lint level is defined here --> $DIR/unused-doc-comments-for-macros.rs:1:9 | @@ -30,27 +28,12 @@ LL | #![deny(unused_doc_comments)] error: unused doc comment --> $DIR/unused-doc-comments-for-macros.rs:13:5 | -LL | / /// line1 -LL | | /// line2 -LL | | /// line3 - | |_____--------^ - | | - | rustdoc does not generate documentation for macro invocations +LL | /// line1 + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ rustdoc does not generate documentation for macro calls +... +LL | foo!(); | - = help: to document an item produced by a macro, the macro must produce the documentation as part of its expansion + = help: use `//` for a plain comment -error: unused doc comment - --> $DIR/unused-doc-comments-for-macros.rs:19:5 - | -LL | / #[doc = { -LL | | let a = 1; -LL | | let b = 1; -LL | | let sum = a + b; -LL | | assert_eq!(sum, 2); -LL | | }] - | |______^ rustdoc does not generate documentation for macro invocations - | - = help: to document an item produced by a macro, the macro must produce the documentation as part of its expansion - -error: aborting due to 4 previous errors +error: aborting due to 3 previous errors diff --git a/tests/ui/lint/unused/useless-comment.rs b/tests/ui/lint/unused/useless-comment.rs index 24ff917520814..d04d0a4c116da 100644 --- a/tests/ui/lint/unused/useless-comment.rs +++ b/tests/ui/lint/unused/useless-comment.rs @@ -11,13 +11,16 @@ macro_rules! mac { mac!(); /// a //~ ERROR unused doc comment -#[doc(test(attr(allow(dead_code))))] //~ ERROR unused doc comment +#[doc(test(attr(allow(dead_code))))] +//~^ ERROR `doc` attribute cannot be used on +//~| WARN previously accepted unsafe extern "C" { } fn foo() { /// a //~ ERROR unused doc comment #[doc(test(attr(allow(dead_code))))] - //~^ ERROR unused doc comment + //~^ ERROR `doc` attribute cannot be used on + //~| WARN previously accepted let x = 12; /// multi-line //~ ERROR unused doc comment @@ -27,7 +30,8 @@ fn foo() { /// c //~ ERROR unused doc comment 1 => {}, #[doc(test(attr(allow(dead_code))))] - //~^ ERROR unused doc comment + //~^ ERROR `doc` attribute cannot be used on + //~| WARN previously accepted _ => {} } @@ -42,7 +46,8 @@ fn foo() { mac!(); #[doc(test(attr(allow(dead_code))))] - //~^ ERROR unused doc comment + //~^ ERROR `doc` attribute cannot be used on + //~| WARN previously accepted let x = /** comment */ 47; //~ ERROR unused doc comment /// dox //~ ERROR unused doc comment diff --git a/tests/ui/lint/unused/useless-comment.stderr b/tests/ui/lint/unused/useless-comment.stderr index 22e63caf607a3..a7cafc916430c 100644 --- a/tests/ui/lint/unused/useless-comment.stderr +++ b/tests/ui/lint/unused/useless-comment.stderr @@ -2,9 +2,10 @@ error: unused doc comment --> $DIR/useless-comment.rs:10:1 | LL | /// foo - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ rustdoc does not generate documentation for macro invocations + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ rustdoc does not generate documentation for macro calls +LL | mac!(); | - = help: to document an item produced by a macro, the macro must produce the documentation as part of its expansion + = help: use `//` for a plain comment note: the lint level is defined here --> $DIR/useless-comment.rs:3:9 | @@ -12,154 +13,139 @@ LL | #![deny(unused_doc_comments)] | ^^^^^^^^^^^^^^^^^^^ error: unused doc comment - --> $DIR/useless-comment.rs:13:1 + --> $DIR/useless-comment.rs:45:5 | -LL | /// a - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ -LL | #[doc(test(attr(allow(dead_code))))] -LL | unsafe extern "C" { } - | --------------------- rustdoc does not generate documentation for extern blocks +LL | /// bar + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ rustdoc does not generate documentation for macro calls +LL | mac!(); | = help: use `//` for a plain comment error: unused doc comment - --> $DIR/useless-comment.rs:14:1 + --> $DIR/useless-comment.rs:13:1 | -LL | #[doc(test(attr(allow(dead_code))))] - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +LL | /// a + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ rustdoc does not generate documentation for foreign modules +... LL | unsafe extern "C" { } - | --------------------- rustdoc does not generate documentation for extern blocks | = help: use `//` for a plain comment -error: unused doc comment - --> $DIR/useless-comment.rs:41:5 +error: the `doc` attribute cannot be used on foreign modules + --> $DIR/useless-comment.rs:14:3 | -LL | /// bar - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ rustdoc does not generate documentation for macro invocations +LL | #[doc(test(attr(allow(dead_code))))] + | ^^^ +... +LL | unsafe extern "C" { } | - = help: to document an item produced by a macro, the macro must produce the documentation as part of its expansion + = help: the `doc` attribute can be applied to associated consts, associated types, constants, crates, data types, enum variants, extern crates, foreign statics, functions, impl blocks, macro defs, modules, statics, struct fields, trait aliases, traits, type aliases, and use statements + = warning: this was previously accepted by the compiler but is being phased out; it will become a hard error in a future release! error: unused doc comment - --> $DIR/useless-comment.rs:18:5 + --> $DIR/useless-comment.rs:20:5 | LL | /// a - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ rustdoc does not generate documentation for statements ... LL | let x = 12; - | ----------- rustdoc does not generate documentation for statements | = help: use `//` for a plain comment -error: unused doc comment - --> $DIR/useless-comment.rs:19:5 +error: the `doc` attribute cannot be used on statements + --> $DIR/useless-comment.rs:21:7 | LL | #[doc(test(attr(allow(dead_code))))] - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ -LL | + | ^^^ +... LL | let x = 12; - | ----------- rustdoc does not generate documentation for statements | - = help: use `//` for a plain comment + = help: the `doc` attribute can be applied to associated consts, associated types, constants, crates, data types, enum variants, extern crates, foreign statics, functions, impl blocks, macro defs, modules, statics, struct fields, trait aliases, traits, type aliases, and use statements + = warning: this was previously accepted by the compiler but is being phased out; it will become a hard error in a future release! error: unused doc comment - --> $DIR/useless-comment.rs:23:5 - | -LL | / /// multi-line -LL | | /// doc comment -LL | | /// that is unused - | |______________________^ -LL | / match x { -LL | | /// c -LL | | 1 => {}, -LL | | #[doc(test(attr(allow(dead_code))))] -LL | | -LL | | _ => {} -LL | | } - | |_____- rustdoc does not generate documentation for expressions + --> $DIR/useless-comment.rs:26:5 + | +LL | /// multi-line + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ rustdoc does not generate documentation for expressions +... +LL | match x { | = help: use `//` for a plain comment error: unused doc comment - --> $DIR/useless-comment.rs:27:9 + --> $DIR/useless-comment.rs:30:9 | LL | /// c - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ rustdoc does not generate documentation for match arms LL | 1 => {}, - | ------- rustdoc does not generate documentation for match arms | = help: use `//` for a plain comment -error: unused doc comment - --> $DIR/useless-comment.rs:29:9 +error: the `doc` attribute cannot be used on match arms + --> $DIR/useless-comment.rs:32:11 | LL | #[doc(test(attr(allow(dead_code))))] - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ -LL | + | ^^^ +... LL | _ => {} - | ------- rustdoc does not generate documentation for match arms | - = help: use `//` for a plain comment + = help: the `doc` attribute can be applied to associated consts, associated types, constants, crates, data types, enum variants, extern crates, foreign statics, functions, impl blocks, macro defs, modules, statics, struct fields, trait aliases, traits, type aliases, and use statements + = warning: this was previously accepted by the compiler but is being phased out; it will become a hard error in a future release! error: unused doc comment - --> $DIR/useless-comment.rs:34:5 + --> $DIR/useless-comment.rs:38:5 | LL | /// foo - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ rustdoc does not generate documentation for expressions LL | unsafe {} - | --------- rustdoc does not generate documentation for expressions | = help: use `//` for a plain comment error: unused doc comment - --> $DIR/useless-comment.rs:37:5 + --> $DIR/useless-comment.rs:41:5 | LL | #[doc = "foo"] - | ^^^^^^^^^^^^^^ + | ^^^^^^^^^^^^^^ rustdoc does not generate documentation for expressions LL | #[doc = "bar"] LL | 3; - | - rustdoc does not generate documentation for expressions | = help: use `//` for a plain comment error: unused doc comment - --> $DIR/useless-comment.rs:38:5 + --> $DIR/useless-comment.rs:42:5 | LL | #[doc = "bar"] - | ^^^^^^^^^^^^^^ + | ^^^^^^^^^^^^^^ rustdoc does not generate documentation for expressions LL | 3; - | - rustdoc does not generate documentation for expressions | = help: use `//` for a plain comment error: unused doc comment - --> $DIR/useless-comment.rs:44:5 + --> $DIR/useless-comment.rs:51:13 | -LL | #[doc(test(attr(allow(dead_code))))] - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ -LL | LL | let x = /** comment */ 47; - | -------------------------- rustdoc does not generate documentation for statements + | ^^^^^^^^^^^^^^ rustdoc does not generate documentation for expressions | - = help: use `//` for a plain comment + = help: use `/* */` for a plain comment -error: unused doc comment - --> $DIR/useless-comment.rs:46:13 +error: the `doc` attribute cannot be used on statements + --> $DIR/useless-comment.rs:48:7 | +LL | #[doc(test(attr(allow(dead_code))))] + | ^^^ +... LL | let x = /** comment */ 47; - | ^^^^^^^^^^^^^^ -- rustdoc does not generate documentation for expressions | - = help: use `/* */` for a plain comment + = help: the `doc` attribute can be applied to associated consts, associated types, constants, crates, data types, enum variants, extern crates, foreign statics, functions, impl blocks, macro defs, modules, statics, struct fields, trait aliases, traits, type aliases, and use statements + = warning: this was previously accepted by the compiler but is being phased out; it will become a hard error in a future release! error: unused doc comment - --> $DIR/useless-comment.rs:48:5 - | -LL | /// dox - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ -LL | / { -LL | | -LL | | } - | |_____- rustdoc does not generate documentation for expressions + --> $DIR/useless-comment.rs:53:5 + | +LL | /// dox + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ rustdoc does not generate documentation for expressions +LL | { | = help: use `//` for a plain comment diff --git a/tests/ui/parser/type-parameters-in-field-exprs.stderr b/tests/ui/parser/type-parameters-in-field-exprs.stderr index ce7364d3534f6..5a15e7ca29021 100644 --- a/tests/ui/parser/type-parameters-in-field-exprs.stderr +++ b/tests/ui/parser/type-parameters-in-field-exprs.stderr @@ -11,10 +11,10 @@ LL | f.x::<>; | ^^ error: field expressions cannot have generic arguments - --> $DIR/type-parameters-in-field-exprs.rs:15:7 + --> $DIR/type-parameters-in-field-exprs.rs:15:10 | LL | f.x::(); - | ^^^^^ + | ^^ error: aborting due to 3 previous errors diff --git a/tests/ui/rustdoc/check-doc-alias-attr-location.stderr b/tests/ui/rustdoc/check-doc-alias-attr-location.stderr index 815bec9f184a9..c7303fe4f01a6 100644 --- a/tests/ui/rustdoc/check-doc-alias-attr-location.stderr +++ b/tests/ui/rustdoc/check-doc-alias-attr-location.stderr @@ -1,8 +1,10 @@ -error: `#[doc(...)]` isn't allowed on parameters - --> $DIR/check-doc-alias-attr-location.rs:22:12 +error: the `doc` attribute cannot be used on function params + --> $DIR/check-doc-alias-attr-location.rs:22:14 | LL | fn foo(#[doc(alias = "qux")] _x: u32) -> Self::X { - | ^^^^^^^^^^^^^^^^^^^^^ + | ^^^ + | + = help: the `doc` attribute can be applied to associated consts, associated types, constants, crates, data types, enum variants, extern crates, foreign statics, functions, impl blocks, macro defs, modules, statics, struct fields, trait aliases, traits, type aliases, and use statements error: `#[doc(alias = "...")]` isn't allowed on foreign module --> $DIR/check-doc-alias-attr-location.rs:9:15 diff --git a/tests/ui/std/is_arch_feature_detected.AARCH64.stderr b/tests/ui/std/is_arch_feature_detected.AARCH64.stderr index d5452993d2573..8dc6ff24c0b62 100644 --- a/tests/ui/std/is_arch_feature_detected.AARCH64.stderr +++ b/tests/ui/std/is_arch_feature_detected.AARCH64.stderr @@ -54,7 +54,8 @@ LL | let _ = arch::is_mips_feature_detected!("msa"); error: This macro cannot be used on the current target. You can prevent it from being used in other architectures by guarding it behind - a `cfg(target_arch = "mips")`. + a `cfg(any(target_arch = "mips", target_arch = "mips32r6", target_arch = "mips64", + target_arch = "mips64r6"))`. --> $DIR/is_arch_feature_detected.rs:41:13 | LL | let _ = arch::is_mips_feature_detected!("msa"); diff --git a/tests/ui/std/is_arch_feature_detected.X86.stderr b/tests/ui/std/is_arch_feature_detected.X86.stderr index 50105408bf422..319b15874d4c2 100644 --- a/tests/ui/std/is_arch_feature_detected.X86.stderr +++ b/tests/ui/std/is_arch_feature_detected.X86.stderr @@ -44,7 +44,8 @@ LL | let _ = arch::is_mips_feature_detected!("msa"); error: This macro cannot be used on the current target. You can prevent it from being used in other architectures by guarding it behind - a `cfg(target_arch = "mips")`. + a `cfg(any(target_arch = "mips", target_arch = "mips32r6", target_arch = "mips64", + target_arch = "mips64r6"))`. --> $DIR/is_arch_feature_detected.rs:41:13 | LL | let _ = arch::is_mips_feature_detected!("msa"); diff --git a/tests/ui/suggestions/suggest-create-closure-issue-150701.fixed b/tests/ui/suggestions/suggest-create-closure-issue-150701.fixed index f3e226c9e5681..d19ab19f98012 100644 --- a/tests/ui/suggestions/suggest-create-closure-issue-150701.fixed +++ b/tests/ui/suggestions/suggest-create-closure-issue-150701.fixed @@ -9,7 +9,6 @@ fn f(_c: impl Future) {} fn main() { f((async || {})()); //~ ERROR: expected function, found `()` - //~^ ERROR: is not a future f(async {}); //~^ ERROR: is not a future } diff --git a/tests/ui/suggestions/suggest-create-closure-issue-150701.rs b/tests/ui/suggestions/suggest-create-closure-issue-150701.rs index e7a5076d8f1d9..bbb5f4d0bb6bd 100644 --- a/tests/ui/suggestions/suggest-create-closure-issue-150701.rs +++ b/tests/ui/suggestions/suggest-create-closure-issue-150701.rs @@ -9,7 +9,6 @@ fn f(_c: impl Future) {} fn main() { f(async || {}()); //~ ERROR: expected function, found `()` - //~^ ERROR: is not a future f(async || {}); //~^ ERROR: is not a future } diff --git a/tests/ui/suggestions/suggest-create-closure-issue-150701.stderr b/tests/ui/suggestions/suggest-create-closure-issue-150701.stderr index 0f991169d6772..8f1f721f97f35 100644 --- a/tests/ui/suggestions/suggest-create-closure-issue-150701.stderr +++ b/tests/ui/suggestions/suggest-create-closure-issue-150701.stderr @@ -11,30 +11,15 @@ help: if you meant to create this closure and immediately call it, surround the LL | f((async || {})()); | + + -error[E0277]: `{async closure@$DIR/suggest-create-closure-issue-150701.rs:11:7: 11:15}` is not a future - --> $DIR/suggest-create-closure-issue-150701.rs:11:7 - | -LL | f(async || {}()); - | - ^^^^^^^^^^^^^ `{async closure@$DIR/suggest-create-closure-issue-150701.rs:11:7: 11:15}` is not a future - | | - | required by a bound introduced by this call - | - = help: the trait `Future` is not implemented for `{async closure@$DIR/suggest-create-closure-issue-150701.rs:11:7: 11:15}` -note: required by a bound in `f` - --> $DIR/suggest-create-closure-issue-150701.rs:8:15 - | -LL | fn f(_c: impl Future) {} - | ^^^^^^^^^^^^^^^^^^^ required by this bound in `f` - -error[E0277]: `{async closure@$DIR/suggest-create-closure-issue-150701.rs:13:7: 13:15}` is not a future - --> $DIR/suggest-create-closure-issue-150701.rs:13:7 +error[E0277]: `{async closure@$DIR/suggest-create-closure-issue-150701.rs:12:7: 12:15}` is not a future + --> $DIR/suggest-create-closure-issue-150701.rs:12:7 | LL | f(async || {}); - | - ^^^^^^^^^^^ `{async closure@$DIR/suggest-create-closure-issue-150701.rs:13:7: 13:15}` is not a future + | - ^^^^^^^^^^^ `{async closure@$DIR/suggest-create-closure-issue-150701.rs:12:7: 12:15}` is not a future | | | required by a bound introduced by this call | - = help: the trait `Future` is not implemented for `{async closure@$DIR/suggest-create-closure-issue-150701.rs:13:7: 13:15}` + = help: the trait `Future` is not implemented for `{async closure@$DIR/suggest-create-closure-issue-150701.rs:12:7: 12:15}` note: required by a bound in `f` --> $DIR/suggest-create-closure-issue-150701.rs:8:15 | @@ -46,7 +31,7 @@ LL - f(async || {}); LL + f(async {}); | -error: aborting due to 3 previous errors +error: aborting due to 2 previous errors Some errors have detailed explanations: E0277, E0618. For more information about an error, try `rustc --explain E0277`. diff --git a/tests/ui/typeck/parenthesized-type-params-in-paths.stderr b/tests/ui/typeck/parenthesized-type-params-in-paths.stderr index f22d9c06edead..68ed444755ac4 100644 --- a/tests/ui/typeck/parenthesized-type-params-in-paths.stderr +++ b/tests/ui/typeck/parenthesized-type-params-in-paths.stderr @@ -71,10 +71,10 @@ LL + fn issue_161062() -> A {} | error: parenthesized generic arguments cannot be used in associated type constraints - --> $DIR/parenthesized-type-params-in-paths.rs:52:58 + --> $DIR/parenthesized-type-params-in-paths.rs:52:63 | LL | fn issue_161062_assoc_constraint() -> &'static dyn Trait { - | ^^^^^^^^^^^^^^^^^ + | ^^^^^^^^^^^^ | help: use angle brackets instead |