about summary refs log tree commit diff
path: root/compiler/rustc_builtin_macros
diff options
context:
space:
mode:
authorBoxy <rust@boxyuwu.dev>2025-02-25 21:27:44 +0000
committerBoxy <rust@boxyuwu.dev>2025-02-25 21:27:44 +0000
commitd9683df7c2f6d4141b1321e27635d2ce3167eaa4 (patch)
treedce0d46d1b7d624ec9b9b09b2c1854f6245a5ff4 /compiler/rustc_builtin_macros
parent46392d1661540e256fd9573d8f06c2784a58c983 (diff)
parent4ecd70ddd1039a3954056c1071e40278048476fa (diff)
downloadrust-d9683df7c2f6d4141b1321e27635d2ce3167eaa4.tar.gz
rust-d9683df7c2f6d4141b1321e27635d2ce3167eaa4.zip
Merge from rustc
Diffstat (limited to 'compiler/rustc_builtin_macros')
-rw-r--r--compiler/rustc_builtin_macros/Cargo.toml3
-rw-r--r--compiler/rustc_builtin_macros/src/autodiff.rs1
-rw-r--r--compiler/rustc_builtin_macros/src/contracts.rs23
-rw-r--r--compiler/rustc_builtin_macros/src/deriving/coerce_pointee.rs74
-rw-r--r--compiler/rustc_builtin_macros/src/deriving/generic/mod.rs15
-rw-r--r--compiler/rustc_builtin_macros/src/pattern_type.rs18
-rw-r--r--compiler/rustc_builtin_macros/src/standard_library_imports.rs49
7 files changed, 101 insertions, 82 deletions
diff --git a/compiler/rustc_builtin_macros/Cargo.toml b/compiler/rustc_builtin_macros/Cargo.toml
index b50cb35b8e9..b5f4f2efd1f 100644
--- a/compiler/rustc_builtin_macros/Cargo.toml
+++ b/compiler/rustc_builtin_macros/Cargo.toml
@@ -1,7 +1,7 @@
 [package]
 name = "rustc_builtin_macros"
 version = "0.0.0"
-edition = "2021"
+edition = "2024"
 
 
 [lints.rust]
@@ -20,6 +20,7 @@ rustc_errors = { path = "../rustc_errors" }
 rustc_expand = { path = "../rustc_expand" }
 rustc_feature = { path = "../rustc_feature" }
 rustc_fluent_macro = { path = "../rustc_fluent_macro" }
+rustc_hir = { path = "../rustc_hir" }
 rustc_index = { path = "../rustc_index" }
 rustc_lexer = { path = "../rustc_lexer" }
 rustc_lint_defs = { path = "../rustc_lint_defs" }
diff --git a/compiler/rustc_builtin_macros/src/autodiff.rs b/compiler/rustc_builtin_macros/src/autodiff.rs
index 24c54edd705..8d7ac6de801 100644
--- a/compiler/rustc_builtin_macros/src/autodiff.rs
+++ b/compiler/rustc_builtin_macros/src/autodiff.rs
@@ -242,6 +242,7 @@ mod llvm_enzyme {
             defaultness: ast::Defaultness::Final,
             sig: d_sig,
             generics: Generics::default(),
+            contract: None,
             body: Some(d_body),
         });
         let mut rustc_ad_attr =
diff --git a/compiler/rustc_builtin_macros/src/contracts.rs b/compiler/rustc_builtin_macros/src/contracts.rs
index 85a30f7bdc9..6a24af361fe 100644
--- a/compiler/rustc_builtin_macros/src/contracts.rs
+++ b/compiler/rustc_builtin_macros/src/contracts.rs
@@ -1,11 +1,9 @@
-#![allow(unused_imports, unused_variables)]
-
 use rustc_ast::token;
 use rustc_ast::tokenstream::{DelimSpacing, DelimSpan, Spacing, TokenStream, TokenTree};
 use rustc_errors::ErrorGuaranteed;
 use rustc_expand::base::{AttrProcMacro, ExtCtxt};
 use rustc_span::Span;
-use rustc_span::symbol::{Ident, Symbol, kw, sym};
+use rustc_span::symbol::{Ident, Symbol, kw};
 
 pub(crate) struct ExpandRequires;
 
@@ -121,23 +119,19 @@ fn expand_contract_clause(
         }
     }
 
-    // Record the span as a contract attribute expansion.
-    // This is used later to stop users from using the extended syntax directly
-    // which is gated via `contracts_internals`.
-    ecx.psess().contract_attribute_spans.push(attr_span);
-
     Ok(new_tts)
 }
 
 fn expand_requires_tts(
-    _ecx: &mut ExtCtxt<'_>,
+    ecx: &mut ExtCtxt<'_>,
     attr_span: Span,
     annotation: TokenStream,
     annotated: TokenStream,
 ) -> Result<TokenStream, ErrorGuaranteed> {
-    expand_contract_clause(_ecx, attr_span, annotated, |new_tts| {
+    let feature_span = ecx.with_def_site_ctxt(attr_span);
+    expand_contract_clause(ecx, attr_span, annotated, |new_tts| {
         new_tts.push_tree(TokenTree::Token(
-            token::Token::from_ast_ident(Ident::new(kw::ContractRequires, attr_span)),
+            token::Token::from_ast_ident(Ident::new(kw::ContractRequires, feature_span)),
             Spacing::Joint,
         ));
         new_tts.push_tree(TokenTree::Token(
@@ -155,14 +149,15 @@ fn expand_requires_tts(
 }
 
 fn expand_ensures_tts(
-    _ecx: &mut ExtCtxt<'_>,
+    ecx: &mut ExtCtxt<'_>,
     attr_span: Span,
     annotation: TokenStream,
     annotated: TokenStream,
 ) -> Result<TokenStream, ErrorGuaranteed> {
-    expand_contract_clause(_ecx, attr_span, annotated, |new_tts| {
+    let feature_span = ecx.with_def_site_ctxt(attr_span);
+    expand_contract_clause(ecx, attr_span, annotated, |new_tts| {
         new_tts.push_tree(TokenTree::Token(
-            token::Token::from_ast_ident(Ident::new(kw::ContractEnsures, attr_span)),
+            token::Token::from_ast_ident(Ident::new(kw::ContractEnsures, feature_span)),
             Spacing::Joint,
         ));
         new_tts.push_tree(TokenTree::Delimited(
diff --git a/compiler/rustc_builtin_macros/src/deriving/coerce_pointee.rs b/compiler/rustc_builtin_macros/src/deriving/coerce_pointee.rs
index 82417a86dd9..5aed9f76f14 100644
--- a/compiler/rustc_builtin_macros/src/deriving/coerce_pointee.rs
+++ b/compiler/rustc_builtin_macros/src/deriving/coerce_pointee.rs
@@ -3,11 +3,11 @@ use ast::ptr::P;
 use rustc_ast::mut_visit::MutVisitor;
 use rustc_ast::visit::BoundKind;
 use rustc_ast::{
-    self as ast, GenericArg, GenericBound, GenericParamKind, ItemKind, MetaItem,
+    self as ast, GenericArg, GenericBound, GenericParamKind, Generics, ItemKind, MetaItem,
     TraitBoundModifiers, VariantData, WherePredicate,
 };
-use rustc_attr_parsing as attr;
 use rustc_data_structures::flat_map_in_place::FlatMapInPlace;
+use rustc_errors::E0802;
 use rustc_expand::base::{Annotatable, ExtCtxt};
 use rustc_macros::Diagnostic;
 use rustc_span::{Ident, Span, Symbol, sym};
@@ -32,15 +32,6 @@ pub(crate) fn expand_deriving_coerce_pointee(
     let (name_ident, generics) = if let Annotatable::Item(aitem) = item
         && let ItemKind::Struct(struct_data, g) = &aitem.kind
     {
-        let is_transparent = aitem.attrs.iter().any(|attr| {
-            attr::find_repr_attrs(cx.sess, attr)
-                .into_iter()
-                .any(|r| matches!(r, attr::ReprTransparent))
-        });
-        if !is_transparent {
-            cx.dcx().emit_err(RequireTransparent { span });
-            return;
-        }
         if !matches!(
             struct_data,
             VariantData::Struct { fields, recovered: _ } | VariantData::Tuple(fields, _)
@@ -88,8 +79,7 @@ pub(crate) fn expand_deriving_coerce_pointee(
     } else {
         let mut pointees = type_params
             .iter()
-            .filter_map(|&(idx, span, is_pointee)| is_pointee.then_some((idx, span)))
-            .fuse();
+            .filter_map(|&(idx, span, is_pointee)| is_pointee.then_some((idx, span)));
         match (pointees.next(), pointees.next()) {
             (Some((idx, _span)), None) => idx,
             (None, _) => {
@@ -110,6 +100,52 @@ pub(crate) fn expand_deriving_coerce_pointee(
     // Declare helper function that adds implementation blocks.
     // FIXME(dingxiangfei2009): Investigate the set of attributes on target struct to be propagated to impls
     let attrs = thin_vec![cx.attr_word(sym::automatically_derived, span),];
+    // # Validity assertion which will be checked later in `rustc_hir_analysis::coherence::builtins`.
+    {
+        let trait_path =
+            cx.path_all(span, true, path!(span, core::marker::CoercePointeeValidated), vec![]);
+        let trait_ref = cx.trait_ref(trait_path);
+        push(Annotatable::Item(
+            cx.item(
+                span,
+                Ident::empty(),
+                attrs.clone(),
+                ast::ItemKind::Impl(Box::new(ast::Impl {
+                    safety: ast::Safety::Default,
+                    polarity: ast::ImplPolarity::Positive,
+                    defaultness: ast::Defaultness::Final,
+                    constness: ast::Const::No,
+                    generics: Generics {
+                        params: generics
+                            .params
+                            .iter()
+                            .map(|p| match &p.kind {
+                                GenericParamKind::Lifetime => {
+                                    cx.lifetime_param(p.span(), p.ident, p.bounds.clone())
+                                }
+                                GenericParamKind::Type { default: _ } => {
+                                    cx.typaram(p.span(), p.ident, p.bounds.clone(), None)
+                                }
+                                GenericParamKind::Const { ty, kw_span: _, default: _ } => cx
+                                    .const_param(
+                                        p.span(),
+                                        p.ident,
+                                        p.bounds.clone(),
+                                        ty.clone(),
+                                        None,
+                                    ),
+                            })
+                            .collect(),
+                        where_clause: generics.where_clause.clone(),
+                        span: generics.span,
+                    },
+                    of_trait: Some(trait_ref),
+                    self_ty: self_type.clone(),
+                    items: ThinVec::new(),
+                })),
+            ),
+        ));
+    }
     let mut add_impl_block = |generics, trait_symbol, trait_args| {
         let mut parts = path!(span, core::ops);
         parts.push(Ident::new(trait_symbol, span));
@@ -430,35 +466,35 @@ impl<'a, 'b> rustc_ast::visit::Visitor<'a> for AlwaysErrorOnGenericParam<'a, 'b>
 }
 
 #[derive(Diagnostic)]
-#[diag(builtin_macros_coerce_pointee_requires_transparent)]
+#[diag(builtin_macros_coerce_pointee_requires_transparent, code = E0802)]
 struct RequireTransparent {
     #[primary_span]
     span: Span,
 }
 
 #[derive(Diagnostic)]
-#[diag(builtin_macros_coerce_pointee_requires_one_field)]
+#[diag(builtin_macros_coerce_pointee_requires_one_field, code = E0802)]
 struct RequireOneField {
     #[primary_span]
     span: Span,
 }
 
 #[derive(Diagnostic)]
-#[diag(builtin_macros_coerce_pointee_requires_one_generic)]
+#[diag(builtin_macros_coerce_pointee_requires_one_generic, code = E0802)]
 struct RequireOneGeneric {
     #[primary_span]
     span: Span,
 }
 
 #[derive(Diagnostic)]
-#[diag(builtin_macros_coerce_pointee_requires_one_pointee)]
+#[diag(builtin_macros_coerce_pointee_requires_one_pointee, code = E0802)]
 struct RequireOnePointee {
     #[primary_span]
     span: Span,
 }
 
 #[derive(Diagnostic)]
-#[diag(builtin_macros_coerce_pointee_too_many_pointees)]
+#[diag(builtin_macros_coerce_pointee_too_many_pointees, code = E0802)]
 struct TooManyPointees {
     #[primary_span]
     one: Span,
@@ -467,7 +503,7 @@ struct TooManyPointees {
 }
 
 #[derive(Diagnostic)]
-#[diag(builtin_macros_coerce_pointee_requires_maybe_sized)]
+#[diag(builtin_macros_coerce_pointee_requires_maybe_sized, code = E0802)]
 struct RequiresMaybeSized {
     #[primary_span]
     span: Span,
diff --git a/compiler/rustc_builtin_macros/src/deriving/generic/mod.rs b/compiler/rustc_builtin_macros/src/deriving/generic/mod.rs
index 234ec858216..6b59ac25827 100644
--- a/compiler/rustc_builtin_macros/src/deriving/generic/mod.rs
+++ b/compiler/rustc_builtin_macros/src/deriving/generic/mod.rs
@@ -185,8 +185,9 @@ use rustc_ast::{
     self as ast, AnonConst, BindingMode, ByRef, EnumDef, Expr, GenericArg, GenericParamKind,
     Generics, Mutability, PatKind, VariantData,
 };
-use rustc_attr_parsing as attr;
+use rustc_attr_parsing::{AttributeKind, AttributeParser, ReprPacked};
 use rustc_expand::base::{Annotatable, ExtCtxt};
+use rustc_hir::Attribute;
 use rustc_span::{DUMMY_SP, Ident, Span, Symbol, kw, sym};
 use thin_vec::{ThinVec, thin_vec};
 use ty::{Bounds, Path, Ref, Self_, Ty};
@@ -480,14 +481,10 @@ impl<'a> TraitDef<'a> {
     ) {
         match item {
             Annotatable::Item(item) => {
-                let is_packed = item.attrs.iter().any(|attr| {
-                    for r in attr::find_repr_attrs(cx.sess, attr) {
-                        if let attr::ReprPacked(_) = r {
-                            return true;
-                        }
-                    }
-                    false
-                });
+                let is_packed = matches!(
+                    AttributeParser::parse_limited(cx.sess, &item.attrs, sym::repr, item.span, true),
+                    Some(Attribute::Parsed(AttributeKind::Repr(r))) if r.iter().any(|(x, _)| matches!(x, ReprPacked(..)))
+                );
 
                 let newitem = match &item.kind {
                     ast::ItemKind::Struct(struct_def, generics) => self.expand_struct_def(
diff --git a/compiler/rustc_builtin_macros/src/pattern_type.rs b/compiler/rustc_builtin_macros/src/pattern_type.rs
index a600a9f316a..a55c7e962d0 100644
--- a/compiler/rustc_builtin_macros/src/pattern_type.rs
+++ b/compiler/rustc_builtin_macros/src/pattern_type.rs
@@ -1,6 +1,6 @@
 use rustc_ast::ptr::P;
 use rustc_ast::tokenstream::TokenStream;
-use rustc_ast::{Pat, Ty, ast};
+use rustc_ast::{AnonConst, DUMMY_NODE_ID, Ty, TyPat, TyPatKind, ast};
 use rustc_errors::PResult;
 use rustc_expand::base::{self, DummyResult, ExpandResult, ExtCtxt, MacroExpanderResult};
 use rustc_parse::exp;
@@ -21,12 +21,24 @@ pub(crate) fn expand<'cx>(
     ExpandResult::Ready(base::MacEager::ty(cx.ty(sp, ast::TyKind::Pat(ty, pat))))
 }
 
-fn parse_pat_ty<'a>(cx: &mut ExtCtxt<'a>, stream: TokenStream) -> PResult<'a, (P<Ty>, P<Pat>)> {
+fn parse_pat_ty<'a>(cx: &mut ExtCtxt<'a>, stream: TokenStream) -> PResult<'a, (P<Ty>, P<TyPat>)> {
     let mut parser = cx.new_parser_from_tts(stream);
 
     let ty = parser.parse_ty()?;
     parser.expect_keyword(exp!(Is))?;
-    let pat = parser.parse_pat_no_top_alt(None, None)?;
+    let pat = parser.parse_pat_no_top_alt(None, None)?.into_inner();
+
+    let kind = match pat.kind {
+        ast::PatKind::Range(start, end, include_end) => TyPatKind::Range(
+            start.map(|value| P(AnonConst { id: DUMMY_NODE_ID, value })),
+            end.map(|value| P(AnonConst { id: DUMMY_NODE_ID, value })),
+            include_end,
+        ),
+        ast::PatKind::Err(guar) => TyPatKind::Err(guar),
+        _ => TyPatKind::Err(cx.dcx().span_err(pat.span, "pattern not supported in pattern types")),
+    };
+
+    let pat = P(TyPat { id: pat.id, kind, span: pat.span, tokens: pat.tokens });
 
     Ok((ty, pat))
 }
diff --git a/compiler/rustc_builtin_macros/src/standard_library_imports.rs b/compiler/rustc_builtin_macros/src/standard_library_imports.rs
index 1a3f4d2d449..6933ca09349 100644
--- a/compiler/rustc_builtin_macros/src/standard_library_imports.rs
+++ b/compiler/rustc_builtin_macros/src/standard_library_imports.rs
@@ -19,16 +19,12 @@ pub fn inject(
     let edition = sess.psess.edition;
 
     // the first name in this list is the crate name of the crate with the prelude
-    let names: &[Symbol] = if attr::contains_name(pre_configured_attrs, sym::no_core) {
+    let name: Symbol = if attr::contains_name(pre_configured_attrs, sym::no_core) {
         return 0;
     } else if attr::contains_name(pre_configured_attrs, sym::no_std) {
-        if attr::contains_name(pre_configured_attrs, sym::compiler_builtins) {
-            &[sym::core]
-        } else {
-            &[sym::core, sym::compiler_builtins]
-        }
+        sym::core
     } else {
-        &[sym::std]
+        sym::std
     };
 
     let expn_id = resolver.expansion_for_ast_pass(
@@ -43,36 +39,16 @@ pub fn inject(
     let ecfg = ExpansionConfig::default("std_lib_injection".to_string(), features);
     let cx = ExtCtxt::new(sess, ecfg, resolver, None);
 
-    // .rev() to preserve ordering above in combination with insert(0, ...)
-    for &name in names.iter().rev() {
-        let ident_span = if edition >= Edition2018 { span } else { call_site };
-        let item = if name == sym::compiler_builtins {
-            // compiler_builtins is a private implementation detail. We only
-            // need to insert it into the crate graph for linking and should not
-            // expose any of its public API.
-            //
-            // FIXME(#113634) We should inject this during post-processing like
-            // we do for the panic runtime, profiler runtime, etc.
-            cx.item(
-                span,
-                Ident::new(kw::Underscore, ident_span),
-                thin_vec![],
-                ast::ItemKind::ExternCrate(Some(name)),
-            )
-        } else {
-            cx.item(
-                span,
-                Ident::new(name, ident_span),
-                thin_vec![cx.attr_word(sym::macro_use, span)],
-                ast::ItemKind::ExternCrate(None),
-            )
-        };
-        krate.items.insert(0, item);
-    }
+    let ident_span = if edition >= Edition2018 { span } else { call_site };
 
-    // The crates have been injected, the assumption is that the first one is
-    // the one with the prelude.
-    let name = names[0];
+    let item = cx.item(
+        span,
+        Ident::new(name, ident_span),
+        thin_vec![cx.attr_word(sym::macro_use, span)],
+        ast::ItemKind::ExternCrate(None),
+    );
+
+    krate.items.insert(0, item);
 
     let root = (edition == Edition2015).then_some(kw::PathRoot);
 
@@ -88,6 +64,7 @@ pub fn inject(
         .map(|&symbol| Ident::new(symbol, span))
         .collect();
 
+    // Inject the relevant crate's prelude.
     let use_item = cx.item(
         span,
         Ident::empty(),