Skip to content

Commit f5fff88

Browse files
committed
EII lowering
1 parent dec5682 commit f5fff88

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,7 +2,7 @@ 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::{
@@ -11,6 +11,7 @@ use rustc_hir::{
1111
use rustc_index::{IndexSlice, IndexVec};
1212
use rustc_middle::span_bug;
1313
use rustc_middle::ty::{ResolverAstLowering, TyCtxt};
14+
use rustc_span::def_id::DefId;
1415
use rustc_span::edit_distance::find_best_match_for_name;
1516
use rustc_span::{DUMMY_SP, DesugaringKind, Ident, Span, Symbol, kw, sym};
1617
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(),
@@ -469,6 +552,16 @@ impl<'hir> LoweringContext<'_, 'hir> {
469552
}
470553
}
471554

555+
fn lower_path_simple_eii(&mut self, id: NodeId, path: &Path) -> Option<DefId> {
556+
let res = self.resolver.get_partial_res(id)?;
557+
let Some(did) = res.expect_full_res().opt_def_id() else {
558+
self.dcx().span_delayed_bug(path.span, "should have errored in resolve");
559+
return None;
560+
};
561+
562+
Some(did)
563+
}
564+
472565
#[instrument(level = "debug", skip(self))]
473566
fn lower_use_tree(
474567
&mut self,

compiler/rustc_ast_lowering/src/lib.rs

Lines changed: 14 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -958,11 +958,23 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> {
958958
target_span: Span,
959959
target: Target,
960960
) -> &'hir [hir::Attribute] {
961-
if attrs.is_empty() {
961+
self.lower_attrs_with_extra(id, attrs, target_span, target, &[])
962+
}
963+
964+
fn lower_attrs_with_extra(
965+
&mut self,
966+
id: HirId,
967+
attrs: &[Attribute],
968+
target_span: Span,
969+
target: Target,
970+
extra_hir_attributes: &[hir::Attribute],
971+
) -> &'hir [hir::Attribute] {
972+
if attrs.is_empty() && extra_hir_attributes.is_empty() {
962973
&[]
963974
} else {
964-
let lowered_attrs =
975+
let mut lowered_attrs =
965976
self.lower_attrs_vec(attrs, self.lower_span(target_span), id, target);
977+
lowered_attrs.extend(extra_hir_attributes.iter().cloned());
966978

967979
assert_eq!(id.owner, self.current_hir_id_owner);
968980
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
@@ -17,6 +17,23 @@ use crate::attrs::pretty_printing::PrintAttribute;
1717
use crate::limit::Limit;
1818
use crate::{DefaultBodyStability, PartialConstStability, RustcVersion, Stability};
1919

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

577+
/// Implementation detail of `#[eii]`
578+
EiiExternTarget(EiiDecl),
579+
580+
/// Implementation detail of `#[eii]`
581+
EiiImpls(ThinVec<EiiImpl>),
582+
560583
/// Represents [`#[export_name]`](https://doc.rust-lang.org/reference/abi.html#the-export_name-attribute).
561584
ExportName {
562585
/// 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
@@ -42,6 +42,8 @@ impl AttributeKind {
4242
DoNotImplementViaObject(..) => No,
4343
DocComment { .. } => Yes,
4444
Dummy => No,
45+
EiiExternTarget(_) => Yes,
46+
EiiImpls(..) => No,
4547
ExportName { .. } => Yes,
4648
ExportStable => No,
4749
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;
@@ -149,4 +150,5 @@ print_debug!(
149150
CommentKind,
150151
Transparency,
151152
SanitizerSet,
153+
DefId,
152154
);

compiler/rustc_passes/messages.ftl

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -672,3 +672,18 @@ passes_useless_stability =
672672
this stability annotation is useless
673673
.label = useless stability annotation
674674
.item = the stability attribute annotates this item
675+
676+
passes_eii_fn_with_target_feature =
677+
`#[{$name}]` is not allowed to have `#[target_feature]`
678+
.label = `#[{$name}]` is not allowed to have `#[target_feature]`
679+
680+
passes_eii_fn_with_track_caller =
681+
`#[{$name}]` is not allowed to have `#[track_caller]`
682+
.label = `#[{$name}]` is not allowed to have `#[track_caller]`
683+
684+
passes_eii_impl_not_function =
685+
`eii_macro_for` is only valid on functions
686+
687+
passes_eii_impl_requires_unsafe =
688+
`#[{$name}]` is unsafe to implement
689+
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};
@@ -222,8 +224,12 @@ impl<'tcx> CheckAttrVisitor<'tcx> {
222224
Attribute::Parsed(AttributeKind::MacroExport { span, .. }) => {
223225
self.check_macro_export(hir_id, *span, target)
224226
},
227+
Attribute::Parsed(AttributeKind::EiiImpls(impls)) => {
228+
self.check_eii_impl(impls, target)
229+
},
225230
Attribute::Parsed(
226-
AttributeKind::BodyStability { .. }
231+
AttributeKind::EiiExternTarget { .. }
232+
| AttributeKind::BodyStability { .. }
227233
| AttributeKind::ConstStabilityIndirect
228234
| AttributeKind::MacroTransparency(_)
229235
| AttributeKind::Pointee(..)
@@ -478,6 +484,30 @@ impl<'tcx> CheckAttrVisitor<'tcx> {
478484
);
479485
}
480486

487+
fn check_eii_impl(&self, impls: &[EiiImpl], target: Target) {
488+
for EiiImpl { span, inner_span, eii_macro, impl_marked_unsafe, is_default: _ } in impls {
489+
match target {
490+
Target::Fn => {}
491+
_ => {
492+
self.dcx().emit_err(errors::EiiImplNotFunction { span: *span });
493+
}
494+
}
495+
496+
if find_attr!(self.tcx.get_all_attrs(*eii_macro), AttributeKind::EiiExternTarget(EiiDecl { impl_unsafe, .. }) if *impl_unsafe)
497+
&& !impl_marked_unsafe
498+
{
499+
self.dcx().emit_err(errors::EiiImplRequiresUnsafe {
500+
span: *span,
501+
name: self.tcx.item_name(*eii_macro),
502+
suggestion: errors::EiiImplRequiresUnsafeSuggestion {
503+
left: inner_span.shrink_to_lo(),
504+
right: inner_span.shrink_to_hi(),
505+
},
506+
});
507+
}
508+
}
509+
}
510+
481511
/// Checks if `#[diagnostic::do_not_recommend]` is applied on a trait impl and that it has no
482512
/// arguments.
483513
fn check_do_not_recommend(
@@ -702,6 +732,17 @@ impl<'tcx> CheckAttrVisitor<'tcx> {
702732
sig_span: sig.span,
703733
});
704734
}
735+
736+
if let Some(impls) = find_attr!(attrs, AttributeKind::EiiImpls(impls) => impls) {
737+
let sig = self.tcx.hir_node(hir_id).fn_sig().unwrap();
738+
for i in impls {
739+
self.dcx().emit_err(errors::EiiWithTrackCaller {
740+
attr_span,
741+
name: self.tcx.item_name(i.eii_macro),
742+
sig_span: sig.span,
743+
});
744+
}
745+
}
705746
}
706747
_ => {}
707748
}

compiler/rustc_passes/src/errors.rs

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1469,3 +1469,42 @@ pub(crate) struct CustomMirIncompatibleDialectAndPhase {
14691469
#[label]
14701470
pub phase_span: Span,
14711471
}
1472+
1473+
#[derive(Diagnostic)]
1474+
#[diag(passes_eii_impl_not_function)]
1475+
pub(crate) struct EiiImplNotFunction {
1476+
#[primary_span]
1477+
pub span: Span,
1478+
}
1479+
1480+
#[derive(Diagnostic)]
1481+
#[diag(passes_eii_impl_requires_unsafe)]
1482+
pub(crate) struct EiiImplRequiresUnsafe {
1483+
#[primary_span]
1484+
pub span: Span,
1485+
pub name: Symbol,
1486+
#[subdiagnostic]
1487+
pub suggestion: EiiImplRequiresUnsafeSuggestion,
1488+
}
1489+
1490+
#[derive(Subdiagnostic)]
1491+
#[multipart_suggestion(
1492+
passes_eii_impl_requires_unsafe_suggestion,
1493+
applicability = "machine-applicable"
1494+
)]
1495+
pub(crate) struct EiiImplRequiresUnsafeSuggestion {
1496+
#[suggestion_part(code = "unsafe(")]
1497+
pub left: Span,
1498+
#[suggestion_part(code = ")")]
1499+
pub right: Span,
1500+
}
1501+
1502+
#[derive(Diagnostic)]
1503+
#[diag(passes_eii_fn_with_track_caller)]
1504+
pub(crate) struct EiiWithTrackCaller {
1505+
#[primary_span]
1506+
pub attr_span: Span,
1507+
pub name: Symbol,
1508+
#[label]
1509+
pub sig_span: Span,
1510+
}

0 commit comments

Comments
 (0)