Skip to content

Commit 2aa66a0

Browse files
committed
EII lowering
1 parent d38e969 commit 2aa66a0

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(),
@@ -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
#[instrument(level = "debug", skip(self))]
469562
fn lower_use_tree(
470563
&mut self,

compiler/rustc_ast_lowering/src/lib.rs

Lines changed: 14 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -953,11 +953,23 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> {
953953
target_span: Span,
954954
target: Target,
955955
) -> &'hir [hir::Attribute] {
956-
if attrs.is_empty() {
956+
self.lower_attrs_with_extra(id, attrs, target_span, target, &[])
957+
}
958+
959+
fn lower_attrs_with_extra(
960+
&mut self,
961+
id: HirId,
962+
attrs: &[Attribute],
963+
target_span: Span,
964+
target: Target,
965+
extra_hir_attributes: &[hir::Attribute],
966+
) -> &'hir [hir::Attribute] {
967+
if attrs.is_empty() && extra_hir_attributes.is_empty() {
957968
&[]
958969
} else {
959-
let lowered_attrs =
970+
let mut lowered_attrs =
960971
self.lower_attrs_vec(attrs, self.lower_span(target_span), id, target);
972+
lowered_attrs.extend(extra_hir_attributes.iter().cloned());
961973

962974
assert_eq!(id.owner, self.current_hir_id_owner);
963975
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,
@@ -541,6 +558,12 @@ pub enum AttributeKind {
541558
/// Represents `#[rustc_dummy]`.
542559
Dummy,
543560

561+
/// Implementation detail of `#[eii]`
562+
EiiExternTarget(EiiDecl),
563+
564+
/// Implementation detail of `#[eii]`
565+
EiiImpls(ThinVec<EiiImpl>),
566+
544567
/// Represents [`#[export_name]`](https://doc.rust-lang.org/reference/abi.html#the-export_name-attribute).
545568
ExportName {
546569
/// 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
@@ -661,3 +661,18 @@ passes_useless_stability =
661661
this stability annotation is useless
662662
.label = useless stability annotation
663663
.item = the stability attribute annotates this item
664+
665+
passes_eii_fn_with_target_feature =
666+
`#[{$name}]` is not allowed to have `#[target_feature]`
667+
.label = `#[{$name}]` is not allowed to have `#[target_feature]`
668+
669+
passes_eii_fn_with_track_caller =
670+
`#[{$name}]` is not allowed to have `#[track_caller]`
671+
.label = `#[{$name}]` is not allowed to have `#[track_caller]`
672+
673+
passes_eii_impl_not_function =
674+
`eii_macro_for` is only valid on functions
675+
676+
passes_eii_impl_requires_unsafe =
677+
`#[{$name}]` is unsafe to implement
678+
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::MacroExport { span, .. }) => {
219221
self.check_macro_export(hir_id, *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(..)
@@ -470,6 +476,30 @@ impl<'tcx> CheckAttrVisitor<'tcx> {
470476
);
471477
}
472478

479+
fn check_eii_impl(&self, impls: &[EiiImpl], target: Target) {
480+
for EiiImpl { span, inner_span, eii_macro, impl_marked_unsafe, is_default: _ } in impls {
481+
match target {
482+
Target::Fn => {}
483+
_ => {
484+
self.dcx().emit_err(errors::EiiImplNotFunction { span: *span });
485+
}
486+
}
487+
488+
if find_attr!(self.tcx.get_all_attrs(*eii_macro), AttributeKind::EiiExternTarget(EiiDecl { impl_unsafe, .. }) if *impl_unsafe)
489+
&& !impl_marked_unsafe
490+
{
491+
self.dcx().emit_err(errors::EiiImplRequiresUnsafe {
492+
span: *span,
493+
name: self.tcx.item_name(*eii_macro),
494+
suggestion: errors::EiiImplRequiresUnsafeSuggestion {
495+
left: inner_span.shrink_to_lo(),
496+
right: inner_span.shrink_to_hi(),
497+
},
498+
});
499+
}
500+
}
501+
}
502+
473503
/// Checks if `#[diagnostic::do_not_recommend]` is applied on a trait impl and that it has no
474504
/// arguments.
475505
fn check_do_not_recommend(
@@ -669,6 +699,17 @@ impl<'tcx> CheckAttrVisitor<'tcx> {
669699
sig_span: sig.span,
670700
});
671701
}
702+
703+
if let Some(impls) = find_attr!(attrs, AttributeKind::EiiImpls(impls) => impls) {
704+
let sig = self.tcx.hir_node(hir_id).fn_sig().unwrap();
705+
for i in impls {
706+
self.dcx().emit_err(errors::EiiWithTrackCaller {
707+
attr_span,
708+
name: self.tcx.item_name(i.eii_macro),
709+
sig_span: sig.span,
710+
});
711+
}
712+
}
672713
}
673714
_ => {}
674715
}

compiler/rustc_passes/src/errors.rs

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1457,3 +1457,42 @@ pub(crate) struct CustomMirIncompatibleDialectAndPhase {
14571457
#[label]
14581458
pub phase_span: Span,
14591459
}
1460+
1461+
#[derive(Diagnostic)]
1462+
#[diag(passes_eii_impl_not_function)]
1463+
pub(crate) struct EiiImplNotFunction {
1464+
#[primary_span]
1465+
pub span: Span,
1466+
}
1467+
1468+
#[derive(Diagnostic)]
1469+
#[diag(passes_eii_impl_requires_unsafe)]
1470+
pub(crate) struct EiiImplRequiresUnsafe {
1471+
#[primary_span]
1472+
pub span: Span,
1473+
pub name: Symbol,
1474+
#[subdiagnostic]
1475+
pub suggestion: EiiImplRequiresUnsafeSuggestion,
1476+
}
1477+
1478+
#[derive(Subdiagnostic)]
1479+
#[multipart_suggestion(
1480+
passes_eii_impl_requires_unsafe_suggestion,
1481+
applicability = "machine-applicable"
1482+
)]
1483+
pub(crate) struct EiiImplRequiresUnsafeSuggestion {
1484+
#[suggestion_part(code = "unsafe(")]
1485+
pub left: Span,
1486+
#[suggestion_part(code = ")")]
1487+
pub right: Span,
1488+
}
1489+
1490+
#[derive(Diagnostic)]
1491+
#[diag(passes_eii_fn_with_track_caller)]
1492+
pub(crate) struct EiiWithTrackCaller {
1493+
#[primary_span]
1494+
pub attr_span: Span,
1495+
pub name: Symbol,
1496+
#[label]
1497+
pub sig_span: Span,
1498+
}

0 commit comments

Comments
 (0)