Skip to content

Commit 2e0174e

Browse files
committed
EII lowering
1 parent a308155 commit 2e0174e

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(),
@@ -466,6 +549,16 @@ impl<'hir> LoweringContext<'_, 'hir> {
466549
}
467550
}
468551

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

compiler/rustc_ast_lowering/src/lib.rs

Lines changed: 14 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -956,11 +956,23 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> {
956956
target_span: Span,
957957
target: Target,
958958
) -> &'hir [hir::Attribute] {
959-
if attrs.is_empty() {
959+
self.lower_attrs_with_extra(id, attrs, target_span, target, &[])
960+
}
961+
962+
fn lower_attrs_with_extra(
963+
&mut self,
964+
id: HirId,
965+
attrs: &[Attribute],
966+
target_span: Span,
967+
target: Target,
968+
extra_hir_attributes: &[hir::Attribute],
969+
) -> &'hir [hir::Attribute] {
970+
if attrs.is_empty() && extra_hir_attributes.is_empty() {
960971
&[]
961972
} else {
962-
let lowered_attrs =
973+
let mut lowered_attrs =
963974
self.lower_attrs_vec(attrs, self.lower_span(target_span), id, target);
975+
lowered_attrs.extend(extra_hir_attributes.iter().cloned());
964976

965977
assert_eq!(id.owner, self.current_hir_id_owner);
966978
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,
@@ -522,6 +539,12 @@ pub enum AttributeKind {
522539
/// Represents `#[rustc_dummy]`.
523540
Dummy,
524541

542+
/// Implementation detail of `#[eii]`
543+
EiiExternTarget(EiiDecl),
544+
545+
/// Implementation detail of `#[eii]`
546+
EiiImpls(ThinVec<EiiImpl>),
547+
525548
/// Represents [`#[export_name]`](https://doc.rust-lang.org/reference/abi.html#the-export_name-attribute).
526549
ExportName {
527550
/// 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;
@@ -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
@@ -662,3 +662,18 @@ passes_useless_stability =
662662
this stability annotation is useless
663663
.label = useless stability annotation
664664
.item = the stability attribute annotates this item
665+
666+
passes_eii_fn_with_target_feature =
667+
`#[{$name}]` is not allowed to have `#[target_feature]`
668+
.label = `#[{$name}]` is not allowed to have `#[target_feature]`
669+
670+
passes_eii_fn_with_track_caller =
671+
`#[{$name}]` is not allowed to have `#[track_caller]`
672+
.label = `#[{$name}]` is not allowed to have `#[track_caller]`
673+
674+
passes_eii_impl_not_function =
675+
`eii_macro_for` is only valid on functions
676+
677+
passes_eii_impl_requires_unsafe =
678+
`#[{$name}]` is unsafe to implement
679+
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};
@@ -221,8 +223,12 @@ impl<'tcx> CheckAttrVisitor<'tcx> {
221223
Attribute::Parsed(AttributeKind::MacroExport { span, .. }) => {
222224
self.check_macro_export(hir_id, *span, target)
223225
},
226+
Attribute::Parsed(AttributeKind::EiiImpls(impls)) => {
227+
self.check_eii_impl(impls, target)
228+
},
224229
Attribute::Parsed(
225-
AttributeKind::BodyStability { .. }
230+
AttributeKind::EiiExternTarget { .. }
231+
| AttributeKind::BodyStability { .. }
226232
| AttributeKind::ConstStabilityIndirect
227233
| AttributeKind::MacroTransparency(_)
228234
| AttributeKind::Pointee(..)
@@ -473,6 +479,30 @@ impl<'tcx> CheckAttrVisitor<'tcx> {
473479
);
474480
}
475481

482+
fn check_eii_impl(&self, impls: &[EiiImpl], target: Target) {
483+
for EiiImpl { span, inner_span, eii_macro, impl_marked_unsafe, is_default: _ } in impls {
484+
match target {
485+
Target::Fn => {}
486+
_ => {
487+
self.dcx().emit_err(errors::EiiImplNotFunction { span: *span });
488+
}
489+
}
490+
491+
if find_attr!(self.tcx.get_all_attrs(*eii_macro), AttributeKind::EiiExternTarget(EiiDecl { impl_unsafe, .. }) if *impl_unsafe)
492+
&& !impl_marked_unsafe
493+
{
494+
self.dcx().emit_err(errors::EiiImplRequiresUnsafe {
495+
span: *span,
496+
name: self.tcx.item_name(*eii_macro),
497+
suggestion: errors::EiiImplRequiresUnsafeSuggestion {
498+
left: inner_span.shrink_to_lo(),
499+
right: inner_span.shrink_to_hi(),
500+
},
501+
});
502+
}
503+
}
504+
}
505+
476506
/// Checks if `#[diagnostic::do_not_recommend]` is applied on a trait impl and that it has no
477507
/// arguments.
478508
fn check_do_not_recommend(
@@ -672,6 +702,17 @@ impl<'tcx> CheckAttrVisitor<'tcx> {
672702
sig_span: sig.span,
673703
});
674704
}
705+
706+
if let Some(impls) = find_attr!(attrs, AttributeKind::EiiImpls(impls) => impls) {
707+
let sig = self.tcx.hir_node(hir_id).fn_sig().unwrap();
708+
for i in impls {
709+
self.dcx().emit_err(errors::EiiWithTrackCaller {
710+
attr_span,
711+
name: self.tcx.item_name(i.eii_macro),
712+
sig_span: sig.span,
713+
});
714+
}
715+
}
675716
}
676717
_ => {}
677718
}

compiler/rustc_passes/src/errors.rs

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

0 commit comments

Comments
 (0)