Skip to content

Commit d5a6633

Browse files
Auto merge of #146348 - jdonszelmann:eiiv3, r=<try>
[DONT MERGE] externally implementable items
2 parents 364da5d + f2d2adf commit d5a6633

File tree

120 files changed

+2899
-30
lines changed

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

120 files changed

+2899
-30
lines changed

compiler/rustc_ast/src/ast.rs

Lines changed: 29 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2066,6 +2066,19 @@ pub struct MacroDef {
20662066
pub body: Box<DelimArgs>,
20672067
/// `true` if macro was defined with `macro_rules`.
20682068
pub macro_rules: bool,
2069+
2070+
/// If this is a macro used for externally implementable items,
2071+
/// it refers to an extern item which is its "target". This requires
2072+
/// name resolution so can't just be an attribute, so we store it in this field.
2073+
pub eii_extern_target: Option<EiiExternTarget>,
2074+
}
2075+
2076+
#[derive(Clone, Encodable, Decodable, Debug, HashStable_Generic, Walkable)]
2077+
pub struct EiiExternTarget {
2078+
/// path to the extern item we're targetting
2079+
pub extern_item_path: Path,
2080+
pub impl_unsafe: bool,
2081+
pub span: Span,
20692082
}
20702083

20712084
#[derive(Clone, Encodable, Decodable, Debug, Copy, Hash, Eq, PartialEq)]
@@ -3691,6 +3704,21 @@ pub struct Fn {
36913704
pub contract: Option<Box<FnContract>>,
36923705
pub define_opaque: Option<ThinVec<(NodeId, Path)>>,
36933706
pub body: Option<Box<Block>>,
3707+
3708+
/// This function is an implementation of an externally implementable item (EII).
3709+
/// This means, there was an EII declared somewhere and this function is the
3710+
/// implementation that should be run when the declaration is called.
3711+
pub eii_impls: ThinVec<EiiImpl>,
3712+
}
3713+
3714+
#[derive(Clone, Encodable, Decodable, Debug, Walkable)]
3715+
pub struct EiiImpl {
3716+
pub node_id: NodeId,
3717+
pub eii_macro_path: Path,
3718+
pub impl_safety: Safety,
3719+
pub span: Span,
3720+
pub inner_span: Span,
3721+
pub is_default: bool,
36943722
}
36953723

36963724
#[derive(Clone, Encodable, Decodable, Debug, Walkable)]
@@ -4038,7 +4066,7 @@ mod size_asserts {
40384066
static_assert_size!(Block, 32);
40394067
static_assert_size!(Expr, 72);
40404068
static_assert_size!(ExprKind, 40);
4041-
static_assert_size!(Fn, 184);
4069+
static_assert_size!(Fn, 192);
40424070
static_assert_size!(ForeignItem, 80);
40434071
static_assert_size!(ForeignItemKind, 16);
40444072
static_assert_size!(GenericArg, 24);

compiler/rustc_ast/src/visit.rs

Lines changed: 6 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -392,6 +392,7 @@ macro_rules! common_visitor_and_walkers {
392392
ThinVec<Box<Pat>>,
393393
ThinVec<Box<Ty>>,
394394
ThinVec<Box<TyPat>>,
395+
ThinVec<EiiImpl>,
395396
);
396397

397398
// This macro generates `impl Visitable` and `impl MutVisitable` that forward to `Walkable`
@@ -485,6 +486,8 @@ macro_rules! common_visitor_and_walkers {
485486
WhereEqPredicate,
486487
WhereRegionPredicate,
487488
YieldKind,
489+
EiiExternTarget,
490+
EiiImpl,
488491
);
489492

490493
/// Each method of this trait is a hook to be potentially
@@ -914,13 +917,13 @@ macro_rules! common_visitor_and_walkers {
914917
_ctxt,
915918
// Visibility is visited as a part of the item.
916919
_vis,
917-
Fn { defaultness, ident, sig, generics, contract, body, define_opaque },
920+
Fn { defaultness, ident, sig, generics, contract, body, define_opaque, eii_impls },
918921
) => {
919922
let FnSig { header, decl, span } = sig;
920923
visit_visitable!($($mut)? vis,
921924
defaultness, ident, header, generics, decl,
922-
contract, body, span, define_opaque
923-
)
925+
contract, body, span, define_opaque, eii_impls
926+
);
924927
}
925928
FnKind::Closure(binder, coroutine_kind, decl, body) =>
926929
visit_visitable!($($mut)? vis, binder, coroutine_kind, decl, body),

compiler/rustc_ast_lowering/src/item.rs

Lines changed: 101 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -2,13 +2,14 @@ use rustc_abi::ExternAbi;
22
use rustc_ast::visit::AssocCtxt;
33
use rustc_ast::*;
44
use rustc_errors::{E0570, ErrorGuaranteed, struct_span_code_err};
5-
use rustc_hir::attrs::AttributeKind;
5+
use rustc_hir::attrs::{AttributeKind, EiiDecl};
66
use rustc_hir::def::{DefKind, PerNS, Res};
77
use rustc_hir::def_id::{CRATE_DEF_ID, LocalDefId};
88
use rustc_hir::{self as hir, HirId, LifetimeSource, PredicateOrigin, Target, find_attr};
99
use rustc_index::{IndexSlice, IndexVec};
1010
use rustc_middle::span_bug;
1111
use rustc_middle::ty::{ResolverAstLowering, TyCtxt};
12+
use rustc_span::def_id::DefId;
1213
use rustc_span::edit_distance::find_best_match_for_name;
1314
use rustc_span::{DUMMY_SP, DesugaringKind, Ident, Span, Symbol, kw, sym};
1415
use smallvec::{SmallVec, smallvec};
@@ -133,10 +134,92 @@ impl<'hir> LoweringContext<'_, 'hir> {
133134
}
134135
}
135136

137+
fn generate_extra_attrs_for_item_kind(
138+
&mut self,
139+
id: NodeId,
140+
i: &ItemKind,
141+
) -> Vec<hir::Attribute> {
142+
match i {
143+
ItemKind::Fn(box Fn { eii_impls, .. }) if eii_impls.is_empty() => Vec::new(),
144+
ItemKind::Fn(box Fn { eii_impls, .. }) => {
145+
vec![hir::Attribute::Parsed(AttributeKind::EiiImpls(
146+
eii_impls
147+
.iter()
148+
.flat_map(
149+
|EiiImpl {
150+
node_id,
151+
eii_macro_path,
152+
impl_safety,
153+
span,
154+
inner_span,
155+
is_default,
156+
}| {
157+
self.lower_path_simple_eii(*node_id, eii_macro_path).map(|did| {
158+
hir::attrs::EiiImpl {
159+
eii_macro: did,
160+
span: self.lower_span(*span),
161+
inner_span: self.lower_span(*inner_span),
162+
impl_marked_unsafe: self
163+
.lower_safety(*impl_safety, hir::Safety::Safe)
164+
.is_unsafe(),
165+
is_default: *is_default,
166+
}
167+
})
168+
},
169+
)
170+
.collect(),
171+
))]
172+
}
173+
ItemKind::MacroDef(
174+
_,
175+
MacroDef {
176+
eii_extern_target: Some(EiiExternTarget { extern_item_path, impl_unsafe, span }),
177+
..
178+
},
179+
) => self
180+
.lower_path_simple_eii(id, extern_item_path)
181+
.map(|did| {
182+
vec![hir::Attribute::Parsed(AttributeKind::EiiExternTarget(EiiDecl {
183+
eii_extern_target: did,
184+
impl_unsafe: *impl_unsafe,
185+
span: self.lower_span(*span),
186+
}))]
187+
})
188+
.unwrap_or_default(),
189+
ItemKind::ExternCrate(..)
190+
| ItemKind::Use(..)
191+
| ItemKind::Static(..)
192+
| ItemKind::Const(..)
193+
| ItemKind::Mod(..)
194+
| ItemKind::ForeignMod(..)
195+
| ItemKind::GlobalAsm(..)
196+
| ItemKind::TyAlias(..)
197+
| ItemKind::Enum(..)
198+
| ItemKind::Struct(..)
199+
| ItemKind::Union(..)
200+
| ItemKind::Trait(..)
201+
| ItemKind::TraitAlias(..)
202+
| ItemKind::Impl(..)
203+
| ItemKind::MacCall(..)
204+
| ItemKind::MacroDef(..)
205+
| ItemKind::Delegation(..)
206+
| ItemKind::DelegationMac(..) => Vec::new(),
207+
}
208+
}
209+
136210
fn lower_item(&mut self, i: &Item) -> &'hir hir::Item<'hir> {
137211
let vis_span = self.lower_span(i.vis.span);
138212
let hir_id = hir::HirId::make_owner(self.current_hir_id_owner.def_id);
139-
let attrs = self.lower_attrs(hir_id, &i.attrs, i.span, Target::from_ast_item(i));
213+
214+
let extra_hir_attributes = self.generate_extra_attrs_for_item_kind(i.id, &i.kind);
215+
let attrs = self.lower_attrs_with_extra(
216+
hir_id,
217+
&i.attrs,
218+
i.span,
219+
Target::from_ast_item(i),
220+
&extra_hir_attributes,
221+
);
222+
140223
let kind = self.lower_item_kind(i.span, i.id, hir_id, attrs, vis_span, &i.kind);
141224
let item = hir::Item {
142225
owner_id: hir_id.expect_owner(),
@@ -431,7 +514,7 @@ impl<'hir> LoweringContext<'_, 'hir> {
431514
);
432515
hir::ItemKind::TraitAlias(ident, generics, bounds)
433516
}
434-
ItemKind::MacroDef(ident, MacroDef { body, macro_rules }) => {
517+
ItemKind::MacroDef(ident, MacroDef { body, macro_rules, eii_extern_target: _ }) => {
435518
let ident = self.lower_ident(*ident);
436519
let body = Box::new(self.lower_delim_args(body));
437520
let def_id = self.local_def_id(id);
@@ -442,7 +525,11 @@ impl<'hir> LoweringContext<'_, 'hir> {
442525
def_kind.descr(def_id.to_def_id())
443526
);
444527
};
445-
let macro_def = self.arena.alloc(ast::MacroDef { body, macro_rules: *macro_rules });
528+
let macro_def = self.arena.alloc(ast::MacroDef {
529+
body,
530+
macro_rules: *macro_rules,
531+
eii_extern_target: None,
532+
});
446533
hir::ItemKind::Macro(ident, macro_def, macro_kinds)
447534
}
448535
ItemKind::Delegation(box delegation) => {
@@ -461,6 +548,16 @@ impl<'hir> LoweringContext<'_, 'hir> {
461548
}
462549
}
463550

551+
fn lower_path_simple_eii(&mut self, id: NodeId, path: &Path) -> Option<DefId> {
552+
let res = self.resolver.get_partial_res(id)?;
553+
let Some(did) = res.expect_full_res().opt_def_id() else {
554+
self.dcx().span_delayed_bug(path.span, "should have errored in resolve");
555+
return None;
556+
};
557+
558+
Some(did)
559+
}
560+
464561
fn lower_const_item(
465562
&mut self,
466563
ty: &Ty,

compiler/rustc_ast_lowering/src/lib.rs

Lines changed: 14 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -945,11 +945,23 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> {
945945
target_span: Span,
946946
target: Target,
947947
) -> &'hir [hir::Attribute] {
948-
if attrs.is_empty() {
948+
self.lower_attrs_with_extra(id, attrs, target_span, target, &[])
949+
}
950+
951+
fn lower_attrs_with_extra(
952+
&mut self,
953+
id: HirId,
954+
attrs: &[Attribute],
955+
target_span: Span,
956+
target: Target,
957+
extra_hir_attributes: &[hir::Attribute],
958+
) -> &'hir [hir::Attribute] {
959+
if attrs.is_empty() && extra_hir_attributes.is_empty() {
949960
&[]
950961
} else {
951-
let lowered_attrs =
962+
let mut lowered_attrs =
952963
self.lower_attrs_vec(attrs, self.lower_span(target_span), id, target);
964+
lowered_attrs.extend(extra_hir_attributes.iter().cloned());
953965

954966
assert_eq!(id.owner, self.current_hir_id_owner);
955967
let ret = self.arena.alloc_from_iter(lowered_attrs);

compiler/rustc_ast_passes/src/ast_validation.rs

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1053,11 +1053,16 @@ impl<'a> Visitor<'a> for AstValidator<'a> {
10531053
contract: _,
10541054
body,
10551055
define_opaque: _,
1056+
eii_impls,
10561057
},
10571058
) => {
10581059
self.visit_attrs_vis_ident(&item.attrs, &item.vis, ident);
10591060
self.check_defaultness(item.span, *defaultness);
10601061

1062+
for EiiImpl { eii_macro_path, .. } in eii_impls {
1063+
self.visit_path(eii_macro_path);
1064+
}
1065+
10611066
let is_intrinsic = item.attrs.iter().any(|a| a.has_name(sym::rustc_intrinsic));
10621067
if body.is_none() && !is_intrinsic && !self.is_sdylib_interface {
10631068
self.dcx().emit_err(errors::FnWithoutBody {

compiler/rustc_ast_pretty/src/pprust/state.rs

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -852,6 +852,17 @@ pub trait PrintState<'a>: std::ops::Deref<Target = pp::Printer> + std::ops::Dere
852852
sp: Span,
853853
print_visibility: impl FnOnce(&mut Self),
854854
) {
855+
if let Some(eii_extern_target) = &macro_def.eii_extern_target {
856+
self.word("#[eii_extern_target(");
857+
self.print_path(&eii_extern_target.extern_item_path, false, 0);
858+
if eii_extern_target.impl_unsafe {
859+
self.word(",");
860+
self.space();
861+
self.word("unsafe");
862+
}
863+
self.word(")]");
864+
self.hardbreak();
865+
}
855866
let (kw, has_bang) = if macro_def.macro_rules {
856867
("macro_rules", true)
857868
} else {
@@ -2141,6 +2152,15 @@ impl<'a> State<'a> {
21412152

21422153
fn print_meta_item(&mut self, item: &ast::MetaItem) {
21432154
let ib = self.ibox(INDENT_UNIT);
2155+
2156+
match item.unsafety {
2157+
ast::Safety::Unsafe(_) => {
2158+
self.word("unsafe");
2159+
self.popen();
2160+
}
2161+
ast::Safety::Default | ast::Safety::Safe(_) => {}
2162+
}
2163+
21442164
match &item.kind {
21452165
ast::MetaItemKind::Word => self.print_path(&item.path, false, 0),
21462166
ast::MetaItemKind::NameValue(value) => {
@@ -2156,6 +2176,12 @@ impl<'a> State<'a> {
21562176
self.pclose();
21572177
}
21582178
}
2179+
2180+
match item.unsafety {
2181+
ast::Safety::Unsafe(_) => self.pclose(),
2182+
ast::Safety::Default | ast::Safety::Safe(_) => {}
2183+
}
2184+
21592185
self.end(ib);
21602186
}
21612187

compiler/rustc_ast_pretty/src/pprust/state/item.rs

Lines changed: 17 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,6 @@
11
use ast::StaticItem;
22
use itertools::{Itertools, Position};
3-
use rustc_ast as ast;
4-
use rustc_ast::ModKind;
3+
use rustc_ast::{self as ast, EiiImpl, ModKind, Safety};
54
use rustc_span::Ident;
65

76
use crate::pp::BoxMarker;
@@ -675,10 +674,25 @@ impl<'a> State<'a> {
675674
}
676675

677676
fn print_fn_full(&mut self, vis: &ast::Visibility, attrs: &[ast::Attribute], func: &ast::Fn) {
678-
let ast::Fn { defaultness, ident, generics, sig, contract, body, define_opaque } = func;
677+
let ast::Fn { defaultness, ident, generics, sig, contract, body, define_opaque, eii_impls } =
678+
func;
679679

680680
self.print_define_opaques(define_opaque.as_deref());
681681

682+
for EiiImpl { eii_macro_path, impl_safety, .. } in eii_impls {
683+
self.word("#[");
684+
if let Safety::Unsafe(..) = impl_safety {
685+
self.word("unsafe");
686+
self.popen();
687+
}
688+
self.print_path(eii_macro_path, false, 0);
689+
if let Safety::Unsafe(..) = impl_safety {
690+
self.pclose();
691+
}
692+
self.word("]");
693+
self.hardbreak();
694+
}
695+
682696
let body_cb_ib = body.as_ref().map(|body| (body, self.head("")));
683697

684698
self.print_visibility(vis);

compiler/rustc_builtin_macros/messages.ftl

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -294,3 +294,10 @@ builtin_macros_unexpected_lit = expected path to a trait, found literal
294294
.label = not a trait
295295
.str_lit = try using `#[derive({$sym})]`
296296
.other = for example, write `#[derive(Debug)]` for `Debug`
297+
298+
builtin_macros_eii_shared_macro_expected_function = `#[{$name}]` is only valid on functions
299+
builtin_macros_eii_extern_target_expected_list = `#[eii_extern_target(...)]` expects a list of one or two elements
300+
builtin_macros_eii_extern_target_expected_macro = `#[eii_extern_target(...)]` is only valid on macros
301+
builtin_macros_eii_shared_macro_expected_max_one_argument = `#[{$name}]` expected no arguments or a single argument: `#[{$name}(default)]`
302+
builtin_macros_eii_extern_target_expected_unsafe = expected this argument to be "unsafe"
303+
.note = the second argument is optional

compiler/rustc_builtin_macros/src/alloc_error_handler.rs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -89,6 +89,7 @@ fn generate_handler(cx: &ExtCtxt<'_>, handler: Ident, span: Span, sig_span: Span
8989
contract: None,
9090
body,
9191
define_opaque: None,
92+
eii_impls: ThinVec::new(),
9293
}));
9394

9495
let attrs = thin_vec![cx.attr_word(sym::rustc_std_internal_symbol, span)];

compiler/rustc_builtin_macros/src/autodiff.rs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -345,6 +345,7 @@ mod llvm_enzyme {
345345
contract: None,
346346
body: Some(d_body),
347347
define_opaque: None,
348+
eii_impls: ThinVec::new(),
348349
});
349350
let mut rustc_ad_attr =
350351
Box::new(ast::NormalAttr::from_ident(Ident::with_dummy_span(sym::rustc_autodiff)));

0 commit comments

Comments
 (0)