Skip to content

Commit 673faef

Browse files
committed
EII lowering
1 parent 379ea54 commit 673faef

File tree

8 files changed

+233
-6
lines changed

8 files changed

+233
-6
lines changed

compiler/rustc_ast_lowering/src/item.rs

Lines changed: 95 additions & 2 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(),
@@ -465,6 +548,16 @@ impl<'hir> LoweringContext<'_, 'hir> {
465548
}
466549
}
467550

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+
468561
fn lower_const_item(
469562
&mut self,
470563
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_hir/src/attrs/data_structures.rs

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,23 @@ use thin_vec::ThinVec;
1616
use crate::attrs::pretty_printing::PrintAttribute;
1717
use crate::{DefaultBodyStability, PartialConstStability, RustcVersion, Stability};
1818

19+
#[derive(Copy, Clone, Debug, HashStable_Generic, Encodable, Decodable, PrintAttribute)]
20+
pub struct EiiImpl {
21+
pub eii_macro: DefId,
22+
pub impl_marked_unsafe: bool,
23+
pub span: Span,
24+
pub inner_span: Span,
25+
pub is_default: bool,
26+
}
27+
28+
#[derive(Copy, Clone, Debug, HashStable_Generic, Encodable, Decodable, PrintAttribute)]
29+
pub struct EiiDecl {
30+
pub eii_extern_target: DefId,
31+
/// whether or not it is unsafe to implement this EII
32+
pub impl_unsafe: bool,
33+
pub span: Span,
34+
}
35+
1936
#[derive(Copy, Clone, PartialEq, Encodable, Decodable, Debug, HashStable_Generic, PrintAttribute)]
2037
pub enum InlineAttr {
2138
None,
@@ -502,6 +519,12 @@ pub enum AttributeKind {
502519
/// Represents `#[rustc_dummy]`.
503520
Dummy,
504521

522+
/// Implementation detail of `#[eii]`
523+
EiiExternTarget(EiiDecl),
524+
525+
/// Implementation detail of `#[eii]`
526+
EiiImpls(ThinVec<EiiImpl>),
527+
505528
/// Represents [`#[export_name]`](https://doc.rust-lang.org/reference/abi.html#the-export_name-attribute).
506529
ExportName {
507530
/// The name to export this item with.

compiler/rustc_hir/src/attrs/encode_cross_crate.rs

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -43,6 +43,8 @@ impl AttributeKind {
4343
DoNotImplementViaObject(..) => No,
4444
DocComment { .. } => Yes,
4545
Dummy => No,
46+
EiiExternTarget(_) => Yes,
47+
EiiImpls(..) => No,
4648
ExportName { .. } => Yes,
4749
ExportStable => No,
4850
FfiConst(..) => No,

compiler/rustc_hir/src/attrs/pretty_printing.rs

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@ use rustc_abi::Align;
44
use rustc_ast::token::CommentKind;
55
use rustc_ast::{AttrStyle, IntTy, UintTy};
66
use rustc_ast_pretty::pp::Printer;
7+
use rustc_span::def_id::DefId;
78
use rustc_span::hygiene::Transparency;
89
use rustc_span::{ErrorGuaranteed, Ident, Span, Symbol};
910
use rustc_target::spec::SanitizerSet;
@@ -157,4 +158,5 @@ print_debug!(
157158
CommentKind,
158159
Transparency,
159160
SanitizerSet,
161+
DefId,
160162
);

compiler/rustc_passes/messages.ftl

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -708,3 +708,18 @@ passes_useless_stability =
708708
this stability annotation is useless
709709
.label = useless stability annotation
710710
.item = the stability attribute annotates this item
711+
712+
passes_eii_fn_with_target_feature =
713+
`#[{$name}]` is not allowed to have `#[target_feature]`
714+
.label = `#[{$name}]` is not allowed to have `#[target_feature]`
715+
716+
passes_eii_fn_with_track_caller =
717+
`#[{$name}]` is not allowed to have `#[track_caller]`
718+
.label = `#[{$name}]` is not allowed to have `#[track_caller]`
719+
720+
passes_eii_impl_not_function =
721+
`eii_macro_for` is only valid on functions
722+
723+
passes_eii_impl_requires_unsafe =
724+
`#[{$name}]` is unsafe to implement
725+
passes_eii_impl_requires_unsafe_suggestion = wrap the attribute in `unsafe(...)`

compiler/rustc_passes/src/check_attr.rs

Lines changed: 43 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -18,7 +18,9 @@ use rustc_feature::{
1818
ACCEPTED_LANG_FEATURES, AttributeDuplicates, AttributeType, BUILTIN_ATTRIBUTE_MAP,
1919
BuiltinAttribute,
2020
};
21-
use rustc_hir::attrs::{AttributeKind, InlineAttr, MirDialect, MirPhase, ReprAttr, SanitizerSet};
21+
use rustc_hir::attrs::{
22+
AttributeKind, EiiDecl, EiiImpl, InlineAttr, MirDialect, MirPhase, ReprAttr, SanitizerSet,
23+
};
2224
use rustc_hir::def::DefKind;
2325
use rustc_hir::def_id::LocalModDefId;
2426
use rustc_hir::intravisit::{self, Visitor};
@@ -218,8 +220,12 @@ impl<'tcx> CheckAttrVisitor<'tcx> {
218220
Attribute::Parsed(AttributeKind::Link(_, attr_span)) => {
219221
self.check_link(hir_id, *attr_span, span, target)
220222
}
223+
Attribute::Parsed(AttributeKind::EiiImpls(impls)) => {
224+
self.check_eii_impl(impls, target)
225+
},
221226
Attribute::Parsed(
222-
AttributeKind::BodyStability { .. }
227+
AttributeKind::EiiExternTarget { .. }
228+
| AttributeKind::BodyStability { .. }
223229
| AttributeKind::ConstStabilityIndirect
224230
| AttributeKind::MacroTransparency(_)
225231
| AttributeKind::Pointee(..)
@@ -450,6 +456,30 @@ impl<'tcx> CheckAttrVisitor<'tcx> {
450456
);
451457
}
452458

459+
fn check_eii_impl(&self, impls: &[EiiImpl], target: Target) {
460+
for EiiImpl { span, inner_span, eii_macro, impl_marked_unsafe, is_default: _ } in impls {
461+
match target {
462+
Target::Fn => {}
463+
_ => {
464+
self.dcx().emit_err(errors::EiiImplNotFunction { span: *span });
465+
}
466+
}
467+
468+
if find_attr!(self.tcx.get_all_attrs(*eii_macro), AttributeKind::EiiExternTarget(EiiDecl { impl_unsafe, .. }) if *impl_unsafe)
469+
&& !impl_marked_unsafe
470+
{
471+
self.dcx().emit_err(errors::EiiImplRequiresUnsafe {
472+
span: *span,
473+
name: self.tcx.item_name(*eii_macro),
474+
suggestion: errors::EiiImplRequiresUnsafeSuggestion {
475+
left: inner_span.shrink_to_lo(),
476+
right: inner_span.shrink_to_hi(),
477+
},
478+
});
479+
}
480+
}
481+
}
482+
453483
/// Checks if `#[diagnostic::do_not_recommend]` is applied on a trait impl and that it has no
454484
/// arguments.
455485
fn check_do_not_recommend(
@@ -649,6 +679,17 @@ impl<'tcx> CheckAttrVisitor<'tcx> {
649679
sig_span: sig.span,
650680
});
651681
}
682+
683+
if let Some(impls) = find_attr!(attrs, AttributeKind::EiiImpls(impls) => impls) {
684+
let sig = self.tcx.hir_node(hir_id).fn_sig().unwrap();
685+
for i in impls {
686+
self.dcx().emit_err(errors::EiiWithTrackCaller {
687+
attr_span,
688+
name: self.tcx.item_name(i.eii_macro),
689+
sig_span: sig.span,
690+
});
691+
}
692+
}
652693
}
653694
_ => {}
654695
}

compiler/rustc_passes/src/errors.rs

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1630,3 +1630,42 @@ pub(crate) struct CustomMirIncompatibleDialectAndPhase {
16301630
#[label]
16311631
pub phase_span: Span,
16321632
}
1633+
1634+
#[derive(Diagnostic)]
1635+
#[diag(passes_eii_impl_not_function)]
1636+
pub(crate) struct EiiImplNotFunction {
1637+
#[primary_span]
1638+
pub span: Span,
1639+
}
1640+
1641+
#[derive(Diagnostic)]
1642+
#[diag(passes_eii_impl_requires_unsafe)]
1643+
pub(crate) struct EiiImplRequiresUnsafe {
1644+
#[primary_span]
1645+
pub span: Span,
1646+
pub name: Symbol,
1647+
#[subdiagnostic]
1648+
pub suggestion: EiiImplRequiresUnsafeSuggestion,
1649+
}
1650+
1651+
#[derive(Subdiagnostic)]
1652+
#[multipart_suggestion(
1653+
passes_eii_impl_requires_unsafe_suggestion,
1654+
applicability = "machine-applicable"
1655+
)]
1656+
pub(crate) struct EiiImplRequiresUnsafeSuggestion {
1657+
#[suggestion_part(code = "unsafe(")]
1658+
pub left: Span,
1659+
#[suggestion_part(code = ")")]
1660+
pub right: Span,
1661+
}
1662+
1663+
#[derive(Diagnostic)]
1664+
#[diag(passes_eii_fn_with_track_caller)]
1665+
pub(crate) struct EiiWithTrackCaller {
1666+
#[primary_span]
1667+
pub attr_span: Span,
1668+
pub name: Symbol,
1669+
#[label]
1670+
pub sig_span: Span,
1671+
}

0 commit comments

Comments
 (0)