1use rustc_abi::ExternAbi;
2use rustc_ast::visit::AssocCtxt;
3use rustc_ast::*;
4use rustc_errors::{E0570, ErrorGuaranteed, struct_span_code_err};
5use rustc_hir::attrs::{AttributeKind, EiiImplResolution};
6use rustc_hir::def::{DefKind, PerNS, Res};
7use rustc_hir::{
8 self as hir, CRATE_OWNER_ID, HirId, ImplItemImplKind, LifetimeSource, PredicateOrigin, Target,
9 find_attr,
10};
11use rustc_middle::span_bug;
12use rustc_middle::ty::data_structures::IndexMap;
13use rustc_middle::ty::{ResolverAstLowering, TyCtxt};
14use rustc_span::def_id::{DefId, LocalDefId};
15use rustc_span::edit_distance::find_best_match_for_name;
16use rustc_span::{DUMMY_SP, DesugaringKind, Ident, Span, Symbol, kw, sym};
17use smallvec::SmallVec;
18use thin_vec::ThinVec;
19use tracing::instrument;
20
21use super::diagnostics::{
22 InvalidAbi, InvalidAbiSuggestion, TupleStructWithDefault, UnionWithDefault,
23};
24use super::stability::{enabled_names, gate_unstable_abi};
25use super::{
26 FnDeclKind, GenericArgsMode, ImplTraitContext, ImplTraitPosition, LoweringContext, ParamMode,
27 RelaxedBoundForbiddenReason, RelaxedBoundPolicy, ResolverAstLoweringExt,
28};
29use crate::diagnostics::ConstComptimeFn;
30
31pub(super) struct ItemLowerer<'a, 'hir> {
32 pub(super) tcx: TyCtxt<'hir>,
33 pub(super) resolver: &'a ResolverAstLowering<'hir>,
34}
35
36fn add_ty_alias_where_clause(
40 generics: &mut ast::Generics,
41 after_where_clause: &ast::WhereClause,
42 prefer_first: bool,
43) {
44 generics.where_clause.predicates.extend_from_slice(&after_where_clause.predicates);
45
46 let mut before = (generics.where_clause.has_where_token, generics.where_clause.span);
47 let mut after = (after_where_clause.has_where_token, after_where_clause.span);
48 if !prefer_first {
49 (before, after) = (after, before);
50 }
51 (generics.where_clause.has_where_token, generics.where_clause.span) =
52 if before.0 || !after.0 { before } else { after };
53}
54
55impl<'hir> ItemLowerer<'_, 'hir> {
56 fn with_lctx(
57 &mut self,
58 owner: NodeId,
59 f: impl FnOnce(&mut LoweringContext<'_, 'hir>) -> hir::OwnerNode<'hir>,
60 ) -> hir::MaybeOwner<'hir> {
61 let mut lctx = LoweringContext::new(self.tcx, self.resolver, owner);
62
63 let item = f(&mut lctx);
64 if true {
{
match (&lctx.current_hir_id_owner, &item.def_id()) {
(left_val, right_val) => {
if !(*left_val == *right_val) {
let kind = ::core::panicking::AssertKind::Eq;
::core::panicking::assert_failed(kind, &*left_val,
&*right_val, ::core::option::Option::None);
}
}
}
};
};debug_assert_eq!(lctx.current_hir_id_owner, item.def_id());
65
66 let info = lctx.make_owner_info(item);
67
68 hir::MaybeOwner::Owner(lctx.arena.alloc(info))
69 }
70
71 #[allow(clippy :: suspicious_else_formatting)]
{
let __tracing_attr_span;
let __tracing_attr_guard;
if ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() ||
{ false } {
__tracing_attr_span =
{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("lower_crate",
"rustc_ast_lowering::item", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_ast_lowering/src/item.rs"),
::tracing_core::__macro_support::Option::Some(71u32),
::tracing_core::__macro_support::Option::Some("rustc_ast_lowering::item"),
::tracing_core::field::FieldSet::new(&[],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::SPAN)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let mut interest = ::tracing::subscriber::Interest::never();
if ::tracing::Level::DEBUG <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{ interest = __CALLSITE.interest(); !interest.is_never() }
&&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest) {
let meta = __CALLSITE.metadata();
::tracing::Span::new(meta,
&{ meta.fields().value_set(&[]) })
} else {
let span =
::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
{};
span
}
};
__tracing_attr_guard = __tracing_attr_span.enter();
}
#[warn(clippy :: suspicious_else_formatting)]
{
#[allow(unknown_lints, unreachable_code, clippy ::
diverging_sub_expression, clippy :: empty_loop, clippy ::
let_unit_value, clippy :: let_with_type_underscore, clippy ::
needless_return, clippy :: unreachable)]
if false {
let __tracing_attr_fake_return: hir::MaybeOwner<'hir> = loop {};
return __tracing_attr_fake_return;
}
{
self.with_lctx(CRATE_NODE_ID,
|lctx|
{
if true {
{
match (&lctx.current_hir_id_owner, &CRATE_OWNER_ID) {
(left_val, right_val) => {
if !(*left_val == *right_val) {
let kind = ::core::panicking::AssertKind::Eq;
::core::panicking::assert_failed(kind, &*left_val,
&*right_val, ::core::option::Option::None);
}
}
}
};
};
let module = lctx.lower_mod(&c.items, &c.spans);
lctx.lower_attrs(hir::CRATE_HIR_ID, &c.attrs,
c.spans.inner_span, Target::Crate);
hir::OwnerNode::Crate(module)
})
}
}
}#[instrument(level = "debug", skip(self, c))]
72 pub(super) fn lower_crate(&mut self, c: &Crate) -> hir::MaybeOwner<'hir> {
73 self.with_lctx(CRATE_NODE_ID, |lctx| {
74 debug_assert_eq!(lctx.current_hir_id_owner, CRATE_OWNER_ID);
75 let module = lctx.lower_mod(&c.items, &c.spans);
76 lctx.lower_attrs(hir::CRATE_HIR_ID, &c.attrs, c.spans.inner_span, Target::Crate);
77 hir::OwnerNode::Crate(module)
78 })
79 }
80
81 #[allow(clippy :: suspicious_else_formatting)]
{
let __tracing_attr_span;
let __tracing_attr_guard;
if ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() ||
{ false } {
__tracing_attr_span =
{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("lower_item",
"rustc_ast_lowering::item", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_ast_lowering/src/item.rs"),
::tracing_core::__macro_support::Option::Some(81u32),
::tracing_core::__macro_support::Option::Some("rustc_ast_lowering::item"),
::tracing_core::field::FieldSet::new(&["item"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::SPAN)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let mut interest = ::tracing::subscriber::Interest::never();
if ::tracing::Level::DEBUG <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{ interest = __CALLSITE.interest(); !interest.is_never() }
&&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest) {
let meta = __CALLSITE.metadata();
::tracing::Span::new(meta,
&{
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = meta.fields().iter();
meta.fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&::tracing::field::debug(&item)
as &dyn Value))])
})
} else {
let span =
::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
{};
span
}
};
__tracing_attr_guard = __tracing_attr_span.enter();
}
#[warn(clippy :: suspicious_else_formatting)]
{
#[allow(unknown_lints, unreachable_code, clippy ::
diverging_sub_expression, clippy :: empty_loop, clippy ::
let_unit_value, clippy :: let_with_type_underscore, clippy ::
needless_return, clippy :: unreachable)]
if false {
let __tracing_attr_fake_return: hir::MaybeOwner<'hir> = loop {};
return __tracing_attr_fake_return;
}
{
self.with_lctx(item.id,
|lctx| hir::OwnerNode::Item(lctx.lower_item(item)))
}
}
}#[instrument(level = "debug", skip(self))]
82 pub(super) fn lower_item(&mut self, item: &Item) -> hir::MaybeOwner<'hir> {
83 self.with_lctx(item.id, |lctx| hir::OwnerNode::Item(lctx.lower_item(item)))
84 }
85
86 pub(super) fn lower_trait_item(&mut self, item: &AssocItem) -> hir::MaybeOwner<'hir> {
87 self.with_lctx(item.id, |lctx| hir::OwnerNode::TraitItem(lctx.lower_trait_item(item)))
88 }
89
90 pub(super) fn lower_impl_item(&mut self, item: &AssocItem) -> hir::MaybeOwner<'hir> {
91 self.with_lctx(item.id, |lctx| hir::OwnerNode::ImplItem(lctx.lower_impl_item(item)))
92 }
93
94 pub(super) fn lower_foreign_item(&mut self, item: &ForeignItem) -> hir::MaybeOwner<'hir> {
95 self.with_lctx(item.id, |lctx| hir::OwnerNode::ForeignItem(lctx.lower_foreign_item(item)))
96 }
97}
98
99impl<'hir> LoweringContext<'_, 'hir> {
100 pub(super) fn lower_mod(
101 &mut self,
102 items: &[Box<Item>],
103 spans: &ModSpans,
104 ) -> &'hir hir::Mod<'hir> {
105 self.arena.alloc(hir::Mod {
106 spans: hir::ModSpans {
107 inner_span: self.lower_span(spans.inner_span),
108 inject_use_span: self.lower_span(spans.inject_use_span),
109 },
110 item_ids: self.arena.alloc_from_iter(items.iter().map(|x| self.lower_item_ref(x))),
111 })
112 }
113
114 pub(super) fn lower_item_ref(&mut self, i: &Item) -> hir::ItemId {
115 hir::ItemId { owner_id: self.owner_id(i.id) }
116 }
117
118 fn lower_eii_decl(
119 &mut self,
120 id: NodeId,
121 name: Ident,
122 EiiDecl { foreign_item, impl_unsafe }: &EiiDecl,
123 ) -> Option<hir::attrs::EiiDecl> {
124 self.lower_path_simple_eii(id, foreign_item).map(|did| hir::attrs::EiiDecl {
125 foreign_item: did,
126 impl_unsafe: *impl_unsafe,
127 name,
128 })
129 }
130
131 fn lower_eii_impl(
132 &mut self,
133 EiiImpl {
134 node_id,
135 eii_macro_path,
136 impl_safety,
137 span,
138 inner_span,
139 is_default,
140 known_eii_macro_resolution,
141 }: &EiiImpl,
142 ) -> hir::attrs::EiiImpl {
143 let resolution = if let Some(target) = known_eii_macro_resolution
144 && let Some(decl) = self.lower_eii_decl(
145 *node_id,
146 eii_macro_path.segments.last().expect("at least one segment").ident,
148 target,
149 ) {
150 EiiImplResolution::Known(decl)
151 } else if let Some(macro_did) = self.lower_path_simple_eii(*node_id, eii_macro_path) {
152 EiiImplResolution::Macro(macro_did)
153 } else {
154 EiiImplResolution::Error(
155 self.dcx().span_delayed_bug(*span, "eii never resolved without errors given"),
156 )
157 };
158
159 hir::attrs::EiiImpl {
160 span: self.lower_span(*span),
161 inner_span: self.lower_span(*inner_span),
162 impl_marked_unsafe: self.lower_safety(*impl_safety, hir::Safety::Safe).is_unsafe(),
163 is_default: *is_default,
164 resolution,
165 }
166 }
167
168 fn generate_extra_attrs_for_item_kind(
169 &mut self,
170 id: NodeId,
171 i: &ItemKind,
172 ) -> Vec<hir::Attribute> {
173 match i {
174 ItemKind::Fn(Fn { eii_impls, .. }) | ItemKind::Static(StaticItem { eii_impls, .. })
175 if eii_impls.is_empty() =>
176 {
177 Vec::new()
178 }
179 ItemKind::Fn(Fn { eii_impls, .. }) | ItemKind::Static(StaticItem { eii_impls, .. }) => {
180 ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[hir::Attribute::Parsed(AttributeKind::EiiImpls(eii_impls.iter().map(|i|
self.lower_eii_impl(i)).collect()))]))vec![hir::Attribute::Parsed(AttributeKind::EiiImpls(
181 eii_impls.iter().map(|i| self.lower_eii_impl(i)).collect(),
182 ))]
183 }
184 ItemKind::MacroDef(name, MacroDef { eii_declaration: Some(target), .. }) => self
185 .lower_eii_decl(id, *name, target)
186 .map(|decl| ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[hir::Attribute::Parsed(AttributeKind::EiiDeclaration(decl))]))vec![hir::Attribute::Parsed(AttributeKind::EiiDeclaration(decl))])
187 .unwrap_or_default(),
188
189 ItemKind::ExternCrate(..)
190 | ItemKind::Use(..)
191 | ItemKind::Const(..)
192 | ItemKind::ConstBlock(..)
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
210 fn lower_item(&mut self, i: &Item) -> &'hir hir::Item<'hir> {
211 let owner_id = self.current_hir_id_owner;
212 let hir_id: HirId = owner_id.into();
213 let vis_span = self.lower_span(i.vis.span);
214
215 let extra_hir_attributes = self.generate_extra_attrs_for_item_kind(i.id, &i.kind);
216 let attrs = self.lower_attrs_with_extra(
217 hir_id,
218 &i.attrs,
219 i.span,
220 Target::from_ast_item(i),
221 &extra_hir_attributes,
222 );
223
224 let kind = self.lower_item_kind(i.span, i.id, hir_id, attrs, vis_span, &i.kind);
225 let item = hir::Item {
226 owner_id,
227 kind,
228 vis_span,
229 span: self.lower_span(i.span),
230 eii: {
{
'done:
{
for i in attrs {
#[allow(unused_imports)]
use rustc_hir::attrs::AttributeKind::*;
let i: &rustc_hir::Attribute = i;
match i {
rustc_hir::Attribute::Parsed(EiiImpls(..) |
EiiDeclaration(..)) => {
break 'done Some(());
}
rustc_hir::Attribute::Unparsed(..) =>
{}
#[deny(unreachable_patterns)]
_ => {}
}
}
None
}
}.is_some()
}find_attr!(attrs, EiiImpls(..) | EiiDeclaration(..)),
231 };
232 self.arena.alloc(item)
233 }
234
235 fn lower_item_kind(
236 &mut self,
237 span: Span,
238 id: NodeId,
239 hir_id: hir::HirId,
240 attrs: &'hir [hir::Attribute],
241 vis_span: Span,
242 i: &ItemKind,
243 ) -> hir::ItemKind<'hir> {
244 match i {
245 ItemKind::ExternCrate(orig_name, ident) => {
246 let ident = self.lower_ident(*ident);
247 hir::ItemKind::ExternCrate(*orig_name, ident)
248 }
249 ItemKind::Use(use_tree) => {
250 let prefix =
252 Path { segments: ThinVec::new(), span: use_tree.prefix.span.shrink_to_lo() };
253
254 self.lower_use_tree(use_tree, &prefix, id, vis_span, attrs)
255 }
256 ItemKind::Static(ast::StaticItem {
257 ident,
258 ty,
259 safety: _,
260 mutability: m,
261 expr: e,
262 define_opaque,
263 eii_impls: _,
264 }) => {
265 let ident = self.lower_ident(*ident);
266 let ty = self
267 .lower_ty_alloc(ty, ImplTraitContext::Disallowed(ImplTraitPosition::StaticTy));
268 let body_id = self.lower_const_body(span, e.as_deref());
269 self.lower_define_opaque(hir_id, define_opaque);
270 hir::ItemKind::Static(*m, ident, ty, body_id)
271 }
272 ItemKind::Const(ConstItem {
273 defaultness: _,
274 ident,
275 generics,
276 ty,
277 rhs_kind,
278 define_opaque,
279 }) => {
280 let ident = self.lower_ident(*ident);
281 let (generics, (ty, rhs)) = self.lower_generics(
282 generics,
283 ImplTraitContext::Disallowed(ImplTraitPosition::Generic),
284 |this| {
285 let ty = this.lower_ty_alloc(
286 ty,
287 ImplTraitContext::Disallowed(ImplTraitPosition::ConstTy),
288 );
289 let rhs = this.lower_const_item_rhs(rhs_kind, span);
290 (ty, rhs)
291 },
292 );
293 self.lower_define_opaque(hir_id, &define_opaque);
294 hir::ItemKind::Const(ident, generics, ty, rhs)
295 }
296 ItemKind::ConstBlock(ConstBlockItem { span, id, block }) => hir::ItemKind::Const(
297 self.lower_ident(ConstBlockItem::IDENT),
298 hir::Generics::empty(),
299 self.arena.alloc(self.ty_tup(DUMMY_SP, &[])),
300 hir::ConstItemRhs::Body({
301 let body = hir::Expr {
302 hir_id: self.lower_node_id(*id),
303 kind: hir::ExprKind::Block(self.lower_block(block, false), None),
304 span: self.lower_span(*span),
305 };
306 self.record_body(&[], body)
307 }),
308 ),
309 ItemKind::Fn(Fn {
310 sig: FnSig { decl, header, span: fn_sig_span },
311 ident,
312 generics,
313 body,
314 contract,
315 define_opaque,
316 ..
317 }) => {
318 self.with_new_scopes(*fn_sig_span, |this| {
319 let coroutine_kind = header.coroutine_kind;
324 let body_id = this.lower_maybe_coroutine_body(
325 *fn_sig_span,
326 span,
327 hir_id,
328 decl,
329 coroutine_kind,
330 body.as_deref(),
331 attrs,
332 contract.as_deref(),
333 );
334
335 let itctx = ImplTraitContext::Universal;
336 let (generics, decl) = this.lower_generics(generics, itctx, |this| {
337 this.lower_fn_decl(decl, id, *fn_sig_span, FnDeclKind::Fn, coroutine_kind)
338 });
339 let sig = hir::FnSig {
340 decl,
341 header: this.lower_fn_header(*header, hir::Safety::Safe, attrs),
342 span: this.lower_span(*fn_sig_span),
343 };
344 this.lower_define_opaque(hir_id, define_opaque);
345 let ident = this.lower_ident(*ident);
346 hir::ItemKind::Fn {
347 ident,
348 sig,
349 generics,
350 body: body_id,
351 has_body: body.is_some(),
352 }
353 })
354 }
355 ItemKind::Mod(_, ident, mod_kind) => {
356 let ident = self.lower_ident(*ident);
357 match mod_kind {
358 ModKind::Loaded(items, _, spans) => {
359 hir::ItemKind::Mod(ident, self.lower_mod(items, spans))
360 }
361 ModKind::Unloaded => {
::core::panicking::panic_fmt(format_args!("`mod` items should have been loaded by now"));
}panic!("`mod` items should have been loaded by now"),
362 }
363 }
364 ItemKind::ForeignMod(fm) => hir::ItemKind::ForeignMod {
365 abi: fm.abi.map_or(ExternAbi::FALLBACK, |abi| self.lower_abi(abi)),
366 items: self
367 .arena
368 .alloc_from_iter(fm.items.iter().map(|x| self.lower_foreign_item_ref(x))),
369 },
370 ItemKind::GlobalAsm(asm) => {
371 let asm = self.lower_inline_asm(span, asm);
372 let fake_body =
373 self.lower_body(|this| (&[], this.expr(span, hir::ExprKind::InlineAsm(asm))));
374 hir::ItemKind::GlobalAsm { asm, fake_body }
375 }
376 ItemKind::TyAlias(TyAlias { ident, generics, after_where_clause, ty, .. }) => {
377 let ident = self.lower_ident(*ident);
386 let mut generics = generics.clone();
387 add_ty_alias_where_clause(&mut generics, after_where_clause, true);
388 let (generics, ty) = self.lower_generics(
389 &generics,
390 ImplTraitContext::Disallowed(ImplTraitPosition::Generic),
391 |this| match ty {
392 None => {
393 let guar = this.dcx().span_delayed_bug(
394 span,
395 "expected to lower type alias type, but it was missing",
396 );
397 this.arena.alloc(this.ty(span, hir::TyKind::Err(guar)))
398 }
399 Some(ty) => this.lower_ty_alloc(
400 ty,
401 ImplTraitContext::OpaqueTy {
402 origin: hir::OpaqueTyOrigin::TyAlias {
403 parent: this.owner.def_id,
404 in_assoc_ty: false,
405 },
406 },
407 ),
408 },
409 );
410 hir::ItemKind::TyAlias(ident, generics, ty)
411 }
412 ItemKind::Enum(ident, generics, enum_definition) => {
413 let ident = self.lower_ident(*ident);
414 let (generics, variants) = self.lower_generics(
415 generics,
416 ImplTraitContext::Disallowed(ImplTraitPosition::Generic),
417 |this| {
418 this.arena.alloc_from_iter(
419 enum_definition.variants.iter().map(|x| this.lower_variant(i, x)),
420 )
421 },
422 );
423 hir::ItemKind::Enum(ident, generics, hir::EnumDef { variants })
424 }
425 ItemKind::Struct(ident, generics, struct_def) => {
426 let ident = self.lower_ident(*ident);
427 let (generics, struct_def) = self.lower_generics(
428 generics,
429 ImplTraitContext::Disallowed(ImplTraitPosition::Generic),
430 |this| this.lower_variant_data(hir_id, i, struct_def),
431 );
432 hir::ItemKind::Struct(ident, generics, struct_def)
433 }
434 ItemKind::Union(ident, generics, vdata) => {
435 let ident = self.lower_ident(*ident);
436 let (generics, vdata) = self.lower_generics(
437 generics,
438 ImplTraitContext::Disallowed(ImplTraitPosition::Generic),
439 |this| this.lower_variant_data(hir_id, i, vdata),
440 );
441 hir::ItemKind::Union(ident, generics, vdata)
442 }
443 ItemKind::Impl(Impl {
444 generics: ast_generics,
445 of_trait,
446 self_ty: ty,
447 items: impl_items,
448 constness,
449 }) => {
450 let itctx = ImplTraitContext::Universal;
464 let (generics, (of_trait, lowered_ty)) =
465 self.lower_generics(ast_generics, itctx, |this| {
466 let of_trait = of_trait
467 .as_deref()
468 .map(|of_trait| this.lower_trait_impl_header(of_trait));
469
470 let lowered_ty = this.lower_ty_alloc(
471 ty,
472 ImplTraitContext::Disallowed(ImplTraitPosition::ImplSelf),
473 );
474
475 (of_trait, lowered_ty)
476 });
477
478 let new_impl_items = self
479 .arena
480 .alloc_from_iter(impl_items.iter().map(|item| self.lower_impl_item_ref(item)));
481
482 let constness = self.lower_constness(*constness);
483
484 hir::ItemKind::Impl(hir::Impl {
485 generics,
486 of_trait,
487 self_ty: lowered_ty,
488 items: new_impl_items,
489 constness,
490 })
491 }
492 ItemKind::Trait(Trait {
493 impl_restriction,
494 constness,
495 is_auto,
496 safety,
497 ident,
498 generics,
499 bounds,
500 items,
501 }) => {
502 let constness = self.lower_constness(*constness);
503 let impl_restriction = self.lower_impl_restriction(impl_restriction);
504 let ident = self.lower_ident(*ident);
505 let (generics, (safety, items, bounds)) = self.lower_generics(
506 generics,
507 ImplTraitContext::Disallowed(ImplTraitPosition::Generic),
508 |this| {
509 let bounds = this.lower_param_bounds(
510 bounds,
511 RelaxedBoundPolicy::Forbidden(RelaxedBoundForbiddenReason::SuperTrait),
512 ImplTraitContext::Disallowed(ImplTraitPosition::Bound),
513 );
514 let items = this.arena.alloc_from_iter(
515 items.iter().map(|item| this.lower_trait_item_ref(item)),
516 );
517 let safety = this.lower_safety(*safety, hir::Safety::Safe);
518 (safety, items, bounds)
519 },
520 );
521 hir::ItemKind::Trait {
522 impl_restriction,
523 constness,
524 is_auto: *is_auto,
525 safety,
526 ident,
527 generics,
528 bounds,
529 items,
530 }
531 }
532 ItemKind::TraitAlias(TraitAlias { constness, ident, generics, bounds }) => {
533 let constness = self.lower_constness(*constness);
534 let ident = self.lower_ident(*ident);
535 let (generics, bounds) = self.lower_generics(
536 generics,
537 ImplTraitContext::Disallowed(ImplTraitPosition::Generic),
538 |this| {
539 this.lower_param_bounds(
540 bounds,
541 RelaxedBoundPolicy::Forbidden(RelaxedBoundForbiddenReason::TraitAlias),
542 ImplTraitContext::Disallowed(ImplTraitPosition::Bound),
543 )
544 },
545 );
546 hir::ItemKind::TraitAlias(constness, ident, generics, bounds)
547 }
548 ItemKind::MacroDef(ident, MacroDef { body, macro_rules, eii_declaration: _ }) => {
549 let ident = self.lower_ident(*ident);
550 let body = Box::new(self.lower_delim_args(body));
551 let def_id = self.owner.def_id;
552 let def_kind = self.tcx.def_kind(def_id);
553 let DefKind::Macro(macro_kinds) = def_kind else {
554 {
::core::panicking::panic_fmt(format_args!("internal error: entered unreachable code: {0}",
format_args!("expected DefKind::Macro for macro item, found {0}",
def_kind.descr(def_id.to_def_id()))));
};unreachable!(
555 "expected DefKind::Macro for macro item, found {}",
556 def_kind.descr(def_id.to_def_id())
557 );
558 };
559 let macro_def = self.arena.alloc(ast::MacroDef {
560 body,
561 macro_rules: *macro_rules,
562 eii_declaration: None,
563 });
564 hir::ItemKind::Macro(ident, macro_def, macro_kinds)
565 }
566 ItemKind::Delegation(delegation) => {
567 let delegation_results = self.lower_delegation(delegation);
568 hir::ItemKind::Fn {
569 sig: delegation_results.sig,
570 ident: delegation_results.ident,
571 generics: delegation_results.generics,
572 body: delegation_results.body_id,
573 has_body: true,
574 }
575 }
576 ItemKind::MacCall(..) | ItemKind::DelegationMac(..) => {
577 {
::core::panicking::panic_fmt(format_args!("macros should have been expanded by now"));
}panic!("macros should have been expanded by now")
578 }
579 }
580 }
581
582 fn lower_path_simple_eii(&mut self, id: NodeId, path: &Path) -> Option<DefId> {
583 let res = self.get_partial_res(id)?;
584 let Some(did) = res.expect_full_res().opt_def_id() else {
585 self.dcx().span_delayed_bug(path.span, "should have errored in resolve");
586 return None;
587 };
588
589 Some(did)
590 }
591
592 #[allow(clippy :: suspicious_else_formatting)]
{
let __tracing_attr_span;
let __tracing_attr_guard;
if ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() ||
{ false } {
__tracing_attr_span =
{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("lower_use_tree",
"rustc_ast_lowering::item", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_ast_lowering/src/item.rs"),
::tracing_core::__macro_support::Option::Some(592u32),
::tracing_core::__macro_support::Option::Some("rustc_ast_lowering::item"),
::tracing_core::field::FieldSet::new(&["tree", "prefix",
"id", "vis_span", "attrs"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::SPAN)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let mut interest = ::tracing::subscriber::Interest::never();
if ::tracing::Level::DEBUG <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{ interest = __CALLSITE.interest(); !interest.is_never() }
&&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest) {
let meta = __CALLSITE.metadata();
::tracing::Span::new(meta,
&{
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = meta.fields().iter();
meta.fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&::tracing::field::debug(&tree)
as &dyn Value)),
(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&::tracing::field::debug(&prefix)
as &dyn Value)),
(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&::tracing::field::debug(&id)
as &dyn Value)),
(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&::tracing::field::debug(&vis_span)
as &dyn Value)),
(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&::tracing::field::debug(&attrs)
as &dyn Value))])
})
} else {
let span =
::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
{};
span
}
};
__tracing_attr_guard = __tracing_attr_span.enter();
}
#[warn(clippy :: suspicious_else_formatting)]
{
#[allow(unknown_lints, unreachable_code, clippy ::
diverging_sub_expression, clippy :: empty_loop, clippy ::
let_unit_value, clippy :: let_with_type_underscore, clippy ::
needless_return, clippy :: unreachable)]
if false {
let __tracing_attr_fake_return: hir::ItemKind<'hir> = loop {};
return __tracing_attr_fake_return;
}
{
let path = &tree.prefix;
let segments =
prefix.segments.iter().chain(path.segments.iter()).cloned().collect();
match tree.kind {
UseTreeKind::Simple(rename) => {
let mut ident = tree.ident();
let mut path = Path { segments, span: path.span };
if path.segments.len() > 1 &&
path.segments.last().unwrap().ident.name == kw::SelfLower {
let _ = path.segments.pop();
if rename.is_none() {
ident = path.segments.last().unwrap().ident;
}
}
let res = self.lower_import_res(id, path.span);
let path =
self.lower_use_path(res, &path, ParamMode::Explicit);
let ident = self.lower_ident(ident);
hir::ItemKind::Use(path, hir::UseKind::Single(ident))
}
UseTreeKind::Glob(_) => {
let res = self.expect_full_res(id);
let res = self.lower_res(res);
let res =
match res {
Res::Def(DefKind::Mod | DefKind::Trait, _) => {
PerNS { type_ns: Some(res), value_ns: None, macro_ns: None }
}
Res::Def(DefKind::Enum, _) => {
PerNS { type_ns: None, value_ns: Some(res), macro_ns: None }
}
Res::Err => {
let err = Some(Res::Err);
PerNS { type_ns: err, value_ns: err, macro_ns: err }
}
_ =>
::rustc_middle::util::bug::span_bug_fmt(path.span,
format_args!("bad glob res {0:?}", res)),
};
let path = Path { segments, span: path.span };
let path =
self.lower_use_path(res, &path, ParamMode::Explicit);
hir::ItemKind::Use(path, hir::UseKind::Glob)
}
UseTreeKind::Nested { items: ref trees, .. } => {
let span = prefix.span.to(path.span);
let prefix = Path { segments, span };
for &(ref use_tree, id) in trees {
let owner_id = self.owner_id(id);
self.with_hir_id_owner(id,
|this|
{
let kind =
this.lower_use_tree(use_tree, &prefix, id, vis_span, attrs);
if !attrs.is_empty() {
this.attrs.insert(hir::ItemLocalId::ZERO, attrs);
}
let item =
hir::Item {
owner_id,
kind,
vis_span,
span: this.lower_span(use_tree.span()),
eii: {
{
'done:
{
for i in attrs {
#[allow(unused_imports)]
use rustc_hir::attrs::AttributeKind::*;
let i: &rustc_hir::Attribute = i;
match i {
rustc_hir::Attribute::Parsed(EiiImpls(..) |
EiiDeclaration(..)) => {
break 'done Some(());
}
rustc_hir::Attribute::Unparsed(..) =>
{}
#[deny(unreachable_patterns)]
_ => {}
}
}
None
}
}.is_some()
},
};
hir::OwnerNode::Item(this.arena.alloc(item))
});
}
let path =
if trees.is_empty() &&
!(prefix.segments.is_empty() ||
prefix.segments.len() == 1 &&
prefix.segments[0].ident.name == kw::PathRoot) {
let res = self.lower_import_res(id, span);
self.lower_use_path(res, &prefix, ParamMode::Explicit)
} else {
let span = self.lower_span(span);
self.arena.alloc(hir::UsePath {
res: PerNS::default(),
segments: &[],
span,
})
};
hir::ItemKind::Use(path, hir::UseKind::ListStem)
}
}
}
}
}#[instrument(level = "debug", skip(self))]
593 fn lower_use_tree(
594 &mut self,
595 tree: &UseTree,
596 prefix: &Path,
597 id: NodeId,
598 vis_span: Span,
599 attrs: &'hir [hir::Attribute],
600 ) -> hir::ItemKind<'hir> {
601 let path = &tree.prefix;
602 let segments = prefix.segments.iter().chain(path.segments.iter()).cloned().collect();
603
604 match tree.kind {
605 UseTreeKind::Simple(rename) => {
606 let mut ident = tree.ident();
607
608 let mut path = Path { segments, span: path.span };
610
611 if path.segments.len() > 1
613 && path.segments.last().unwrap().ident.name == kw::SelfLower
614 {
615 let _ = path.segments.pop();
616 if rename.is_none() {
617 ident = path.segments.last().unwrap().ident;
618 }
619 }
620
621 let res = self.lower_import_res(id, path.span);
622 let path = self.lower_use_path(res, &path, ParamMode::Explicit);
623 let ident = self.lower_ident(ident);
624 hir::ItemKind::Use(path, hir::UseKind::Single(ident))
625 }
626 UseTreeKind::Glob(_) => {
627 let res = self.expect_full_res(id);
628 let res = self.lower_res(res);
629 let res = match res {
631 Res::Def(DefKind::Mod | DefKind::Trait, _) => {
632 PerNS { type_ns: Some(res), value_ns: None, macro_ns: None }
633 }
634 Res::Def(DefKind::Enum, _) => {
635 PerNS { type_ns: None, value_ns: Some(res), macro_ns: None }
636 }
637 Res::Err => {
638 let err = Some(Res::Err);
640 PerNS { type_ns: err, value_ns: err, macro_ns: err }
641 }
642 _ => span_bug!(path.span, "bad glob res {:?}", res),
643 };
644 let path = Path { segments, span: path.span };
645 let path = self.lower_use_path(res, &path, ParamMode::Explicit);
646 hir::ItemKind::Use(path, hir::UseKind::Glob)
647 }
648 UseTreeKind::Nested { items: ref trees, .. } => {
649 let span = prefix.span.to(path.span);
674 let prefix = Path { segments, span };
675
676 for &(ref use_tree, id) in trees {
678 let owner_id = self.owner_id(id);
679
680 self.with_hir_id_owner(id, |this| {
686 let kind = this.lower_use_tree(use_tree, &prefix, id, vis_span, attrs);
690 if !attrs.is_empty() {
691 this.attrs.insert(hir::ItemLocalId::ZERO, attrs);
692 }
693
694 let item = hir::Item {
695 owner_id,
696 kind,
697 vis_span,
698 span: this.lower_span(use_tree.span()),
699 eii: find_attr!(attrs, EiiImpls(..) | EiiDeclaration(..)),
700 };
701 hir::OwnerNode::Item(this.arena.alloc(item))
702 });
703 }
704
705 let path = if trees.is_empty()
707 && !(prefix.segments.is_empty()
708 || prefix.segments.len() == 1
709 && prefix.segments[0].ident.name == kw::PathRoot)
710 {
711 let res = self.lower_import_res(id, span);
714 self.lower_use_path(res, &prefix, ParamMode::Explicit)
715 } else {
716 let span = self.lower_span(span);
719 self.arena.alloc(hir::UsePath { res: PerNS::default(), segments: &[], span })
720 };
721 hir::ItemKind::Use(path, hir::UseKind::ListStem)
722 }
723 }
724 }
725
726 fn lower_foreign_item(&mut self, i: &ForeignItem) -> &'hir hir::ForeignItem<'hir> {
727 let owner_id = self.current_hir_id_owner;
728 let hir_id: HirId = owner_id.into();
729 let attrs =
730 self.lower_attrs(hir_id, &i.attrs, i.span, Target::from_foreign_item_kind(&i.kind));
731 let (ident, kind) = match &i.kind {
732 ForeignItemKind::Fn(Fn { sig, ident, generics, define_opaque, .. }) => {
733 let fdec = &sig.decl;
734 let itctx = ImplTraitContext::Universal;
735 let (generics, (decl, fn_args)) = self.lower_generics(generics, itctx, |this| {
736 (
737 this.lower_fn_decl(fdec, i.id, sig.span, FnDeclKind::ExternFn, None),
739 this.lower_fn_params_to_idents(fdec),
740 )
741 });
742
743 let header = self.lower_fn_header(sig.header, hir::Safety::Unsafe, attrs);
745
746 if define_opaque.is_some() {
747 self.dcx().span_err(i.span, "foreign functions cannot define opaque types");
748 }
749
750 (
751 ident,
752 hir::ForeignItemKind::Fn(
753 hir::FnSig { header, decl, span: self.lower_span(sig.span) },
754 fn_args,
755 generics,
756 ),
757 )
758 }
759 ForeignItemKind::Static(StaticItem {
760 ident,
761 ty,
762 mutability,
763 expr: _,
764 safety,
765 define_opaque,
766 eii_impls: _,
767 }) => {
768 let ty = self
769 .lower_ty_alloc(ty, ImplTraitContext::Disallowed(ImplTraitPosition::StaticTy));
770 let safety = self.lower_safety(*safety, hir::Safety::Unsafe);
771 if define_opaque.is_some() {
772 self.dcx().span_err(i.span, "foreign statics cannot define opaque types");
773 }
774 (ident, hir::ForeignItemKind::Static(ty, *mutability, safety))
775 }
776 ForeignItemKind::TyAlias(TyAlias { ident, .. }) => (ident, hir::ForeignItemKind::Type),
777 ForeignItemKind::MacCall(_) => { ::core::panicking::panic_fmt(format_args!("macro shouldn\'t exist here")); }panic!("macro shouldn't exist here"),
778 };
779
780 let item = hir::ForeignItem {
781 owner_id,
782 ident: self.lower_ident(*ident),
783 kind,
784 vis_span: self.lower_span(i.vis.span),
785 span: self.lower_span(i.span),
786 };
787 self.arena.alloc(item)
788 }
789
790 fn lower_foreign_item_ref(&mut self, i: &ForeignItem) -> hir::ForeignItemId {
791 hir::ForeignItemId { owner_id: self.owner_id(i.id) }
792 }
793
794 fn lower_variant(&mut self, item_kind: &ItemKind, v: &Variant) -> hir::Variant<'hir> {
795 if v.ident.name == kw::Underscore && self.tcx.features().unnamed_enum_variants() {
796 self.dcx()
798 .struct_span_fatal(v.span, "unnamed enum variants are not yet implemented")
799 .emit()
800 }
801 let hir_id = self.lower_node_id(v.id);
802 self.lower_attrs(hir_id, &v.attrs, v.span, Target::Variant);
803 hir::Variant {
804 hir_id,
805 def_id: self.local_def_id(v.id),
806 data: self.lower_variant_data(hir_id, item_kind, &v.data),
807 disr_expr: v
808 .disr_expr
809 .as_ref()
810 .map(|e| self.lower_anon_const_to_anon_const(e, e.value.span)),
811 ident: self.lower_ident(v.ident),
812 span: self.lower_span(v.span),
813 }
814 }
815
816 fn lower_variant_data(
817 &mut self,
818 parent_id: hir::HirId,
819 item_kind: &ItemKind,
820 vdata: &VariantData,
821 ) -> hir::VariantData<'hir> {
822 match vdata {
823 VariantData::Struct { fields, recovered } => {
824 let fields = self
825 .arena
826 .alloc_from_iter(fields.iter().enumerate().map(|f| self.lower_field_def(f)));
827
828 if let ItemKind::Union(..) = item_kind {
829 for field in &fields[..] {
830 if let Some(default) = field.default {
831 if self.tcx.features().default_field_values() {
835 self.dcx().emit_err(UnionWithDefault { span: default.span });
836 } else {
837 let _ = self.dcx().span_delayed_bug(
838 default.span,
839 "expected union default field values feature gate error but none \
840 was produced",
841 );
842 }
843 }
844 }
845 }
846
847 hir::VariantData::Struct { fields, recovered: *recovered }
848 }
849 VariantData::Tuple(fields, id) => {
850 let ctor_id = self.lower_node_id(*id);
851 self.alias_attrs(ctor_id, parent_id);
852 let fields = self
853 .arena
854 .alloc_from_iter(fields.iter().enumerate().map(|f| self.lower_field_def(f)));
855 for field in &fields[..] {
856 if let Some(default) = field.default {
857 if self.tcx.features().default_field_values() {
862 self.dcx().emit_err(TupleStructWithDefault { span: default.span });
863 } else {
864 let _ = self.dcx().span_delayed_bug(
865 default.span,
866 "expected `default values on `struct` fields aren't supported` \
867 feature-gate error but none was produced",
868 );
869 }
870 }
871 }
872 hir::VariantData::Tuple(fields, ctor_id, self.local_def_id(*id))
873 }
874 VariantData::Unit(id) => {
875 let ctor_id = self.lower_node_id(*id);
876 self.alias_attrs(ctor_id, parent_id);
877 hir::VariantData::Unit(ctor_id, self.local_def_id(*id))
878 }
879 }
880 }
881
882 pub(super) fn lower_field_def(
883 &mut self,
884 (index, f): (usize, &FieldDef),
885 ) -> hir::FieldDef<'hir> {
886 let ty =
887 self.lower_ty_alloc(&f.ty, ImplTraitContext::Disallowed(ImplTraitPosition::FieldTy));
888 let hir_id = self.lower_node_id(f.id);
889 self.lower_attrs(hir_id, &f.attrs, f.span, Target::Field);
890 hir::FieldDef {
891 span: self.lower_span(f.span),
892 hir_id,
893 def_id: self.local_def_id(f.id),
894 ident: match f.ident {
895 Some(ident) => self.lower_ident(ident),
896 None => Ident::new(sym::integer(index), self.lower_span(f.span)),
898 },
899 vis_span: self.lower_span(f.vis.span),
900 mut_restriction: self.lower_mut_restriction(&f.mut_restriction),
901 default: f
902 .default
903 .as_ref()
904 .map(|v| self.lower_anon_const_to_anon_const(v, v.value.span)),
905 ty,
906 safety: self.lower_safety(f.safety, hir::Safety::Safe),
907 }
908 }
909
910 fn lower_trait_item(&mut self, i: &AssocItem) -> &'hir hir::TraitItem<'hir> {
911 let trait_item_def_id = self.current_hir_id_owner;
912 let hir_id: HirId = trait_item_def_id.into();
913 let attrs = self.lower_attrs(
914 hir_id,
915 &i.attrs,
916 i.span,
917 Target::from_assoc_item_kind(&i.kind, AssocCtxt::Trait),
918 );
919
920 let (ident, generics, kind, has_value) = match &i.kind {
921 AssocItemKind::Const(ConstItem {
922 ident,
923 generics,
924 ty,
925 rhs_kind,
926 define_opaque,
927 ..
928 }) => {
929 let (generics, kind) = self.lower_generics(
930 generics,
931 ImplTraitContext::Disallowed(ImplTraitPosition::Generic),
932 |this| {
933 let ty = this.lower_ty_alloc(
934 ty,
935 ImplTraitContext::Disallowed(ImplTraitPosition::ConstTy),
936 );
937 let rhs = if rhs_kind.has_expr() {
939 Some(this.lower_const_item_rhs(rhs_kind, i.span))
940 } else {
941 None
942 };
943 hir::TraitItemKind::Const(ty, rhs)
944 },
945 );
946
947 if define_opaque.is_some() {
948 if rhs_kind.has_expr() {
949 self.lower_define_opaque(hir_id, &define_opaque);
950 } else {
951 self.dcx().span_err(
952 i.span,
953 "only trait consts with default bodies can define opaque types",
954 );
955 }
956 }
957
958 (*ident, generics, kind, rhs_kind.has_expr())
959 }
960 AssocItemKind::Fn(Fn { sig, ident, generics, body: None, define_opaque, .. }) => {
961 let idents = self.lower_fn_params_to_idents(&sig.decl);
964 let (generics, sig) = self.lower_method_sig(
965 generics,
966 sig,
967 i.id,
968 FnDeclKind::Trait,
969 sig.header.coroutine_kind,
970 attrs,
971 );
972 if define_opaque.is_some() {
973 self.dcx().span_err(
974 i.span,
975 "only trait methods with default bodies can define opaque types",
976 );
977 }
978 (
979 *ident,
980 generics,
981 hir::TraitItemKind::Fn(sig, hir::TraitFn::Required(idents)),
982 false,
983 )
984 }
985 AssocItemKind::Fn(Fn {
986 sig,
987 ident,
988 generics,
989 body: Some(body),
990 contract,
991 define_opaque,
992 ..
993 }) => {
994 let body_id = self.lower_maybe_coroutine_body(
995 sig.span,
996 i.span,
997 hir_id,
998 &sig.decl,
999 sig.header.coroutine_kind,
1000 Some(body),
1001 attrs,
1002 contract.as_deref(),
1003 );
1004 let (generics, sig) = self.lower_method_sig(
1005 generics,
1006 sig,
1007 i.id,
1008 FnDeclKind::Trait,
1009 sig.header.coroutine_kind,
1010 attrs,
1011 );
1012 self.lower_define_opaque(hir_id, &define_opaque);
1013 (
1014 *ident,
1015 generics,
1016 hir::TraitItemKind::Fn(sig, hir::TraitFn::Provided(body_id)),
1017 true,
1018 )
1019 }
1020 AssocItemKind::Type(TyAlias {
1021 ident,
1022 generics,
1023 after_where_clause,
1024 bounds,
1025 ty,
1026 ..
1027 }) => {
1028 let mut generics = generics.clone();
1029 add_ty_alias_where_clause(&mut generics, after_where_clause, false);
1030 let (generics, kind) = self.lower_generics(
1031 &generics,
1032 ImplTraitContext::Disallowed(ImplTraitPosition::Generic),
1033 |this| {
1034 let ty = ty.as_ref().map(|x| {
1035 this.lower_ty_alloc(
1036 x,
1037 ImplTraitContext::Disallowed(ImplTraitPosition::AssocTy),
1038 )
1039 });
1040 hir::TraitItemKind::Type(
1041 this.lower_param_bounds(
1042 bounds,
1043 RelaxedBoundPolicy::Allowed(&mut Default::default()),
1044 ImplTraitContext::Disallowed(ImplTraitPosition::Generic),
1045 ),
1046 ty,
1047 )
1048 },
1049 );
1050 (*ident, generics, kind, ty.is_some())
1051 }
1052 AssocItemKind::Delegation(delegation) => {
1053 let delegation_results = self.lower_delegation(delegation);
1054 let item_kind = hir::TraitItemKind::Fn(
1055 delegation_results.sig,
1056 hir::TraitFn::Provided(delegation_results.body_id),
1057 );
1058 (delegation.ident, delegation_results.generics, item_kind, true)
1059 }
1060 AssocItemKind::MacCall(..) | AssocItemKind::DelegationMac(..) => {
1061 {
::core::panicking::panic_fmt(format_args!("macros should have been expanded by now"));
}panic!("macros should have been expanded by now")
1062 }
1063 };
1064
1065 let defaultness = match i.kind.defaultness() {
1066 Defaultness::Final(..) if !#[allow(non_exhaustive_omitted_patterns)] match i.kind {
AssocItemKind::Fn(..) => true,
_ => false,
}matches!(i.kind, AssocItemKind::Fn(..)) => {
1071 Defaultness::Implicit
1072 }
1073 defaultness => defaultness,
1074 };
1075 let (defaultness, _) = self
1076 .lower_defaultness(defaultness, has_value, || hir::Defaultness::Default { has_value });
1077
1078 let item = hir::TraitItem {
1079 owner_id: trait_item_def_id,
1080 ident: self.lower_ident(ident),
1081 generics,
1082 kind,
1083 span: self.lower_span(i.span),
1084 defaultness,
1085 };
1086 self.arena.alloc(item)
1087 }
1088
1089 fn lower_trait_item_ref(&mut self, i: &AssocItem) -> hir::TraitItemId {
1090 hir::TraitItemId { owner_id: self.owner_id(i.id) }
1091 }
1092
1093 pub(crate) fn expr_err(&mut self, span: Span, guar: ErrorGuaranteed) -> hir::Expr<'hir> {
1095 self.expr(span, hir::ExprKind::Err(guar))
1096 }
1097
1098 fn lower_trait_impl_header(
1099 &mut self,
1100 trait_impl_header: &TraitImplHeader,
1101 ) -> &'hir hir::TraitImplHeader<'hir> {
1102 let TraitImplHeader { safety, polarity, defaultness, ref trait_ref } = *trait_impl_header;
1103 let safety = self.lower_safety(safety, hir::Safety::Safe);
1104 let polarity = match polarity {
1105 ImplPolarity::Positive => ImplPolarity::Positive,
1106 ImplPolarity::Negative(s) => ImplPolarity::Negative(self.lower_span(s)),
1107 };
1108 let has_val = true;
1111 let (defaultness, defaultness_span) =
1112 self.lower_defaultness(defaultness, has_val, || hir::Defaultness::Final);
1113 let modifiers = TraitBoundModifiers {
1114 constness: BoundConstness::Never,
1115 asyncness: BoundAsyncness::Normal,
1116 polarity: BoundPolarity::Positive,
1118 };
1119 let trait_ref = self.lower_trait_ref(
1120 modifiers,
1121 trait_ref,
1122 ImplTraitContext::Disallowed(ImplTraitPosition::Trait),
1123 );
1124
1125 self.arena.alloc(hir::TraitImplHeader {
1126 safety,
1127 polarity,
1128 defaultness,
1129 defaultness_span,
1130 trait_ref,
1131 })
1132 }
1133
1134 fn check_pin_drop_sugar_impl_item(
1135 &self,
1136 i: &AssocItem,
1137 ident: Ident,
1138 trait_item: Result<DefId, ErrorGuaranteed>,
1139 ) -> Ident {
1140 if let AssocItemKind::Fn(fn_kind) = &i.kind
1141 && fn_kind.is_pin_drop_sugar()
1142 {
1143 if let Ok(trait_item) = trait_item
1144 && self
1145 .tcx
1146 .lang_items()
1147 .drop_trait()
1148 .is_none_or(|drop_trait| self.tcx.parent(trait_item) != drop_trait)
1149 {
1150 self.dcx()
1151 .struct_span_err(
1152 i.span,
1153 "method `drop` with `&pin mut self` is only supported for the `Drop` trait",
1154 )
1155 .with_span_label(i.span, "not a `Drop::pin_drop` implementation")
1156 .emit();
1157 }
1158 return Ident::new(sym::pin_drop, ident.span);
1159 }
1160
1161 ident
1162 }
1163
1164 fn lower_impl_item(&mut self, i: &AssocItem) -> &'hir hir::ImplItem<'hir> {
1165 let owner_id = self.current_hir_id_owner;
1166 let hir_id: HirId = owner_id.into();
1167 let parent_id = self.tcx.local_parent(owner_id.def_id);
1168 let is_in_trait_impl =
1169 #[allow(non_exhaustive_omitted_patterns)] match self.tcx.def_kind(parent_id) {
DefKind::Impl { of_trait: true } => true,
_ => false,
}matches!(self.tcx.def_kind(parent_id), DefKind::Impl { of_trait: true });
1170
1171 let has_value = true;
1173 let (defaultness, _) =
1174 self.lower_defaultness(i.kind.defaultness(), has_value, || hir::Defaultness::Final);
1175 let attrs = self.lower_attrs(
1176 hir_id,
1177 &i.attrs,
1178 i.span,
1179 Target::from_assoc_item_kind(&i.kind, AssocCtxt::Impl { of_trait: is_in_trait_impl }),
1180 );
1181
1182 let (ident, (generics, kind)) = match &i.kind {
1183 AssocItemKind::Const(ConstItem {
1184 ident,
1185 generics,
1186 ty,
1187 rhs_kind,
1188 define_opaque,
1189 ..
1190 }) => (
1191 *ident,
1192 self.lower_generics(
1193 generics,
1194 ImplTraitContext::Disallowed(ImplTraitPosition::Generic),
1195 |this| {
1196 let ty = this.lower_ty_alloc(
1197 ty,
1198 ImplTraitContext::Disallowed(ImplTraitPosition::ConstTy),
1199 );
1200 this.lower_define_opaque(hir_id, &define_opaque);
1201 let rhs = this.lower_const_item_rhs(rhs_kind, i.span);
1202 hir::ImplItemKind::Const(ty, rhs)
1203 },
1204 ),
1205 ),
1206 AssocItemKind::Fn(Fn {
1207 sig, ident, generics, body, contract, define_opaque, ..
1208 }) => {
1209 let body_id = self.lower_maybe_coroutine_body(
1210 sig.span,
1211 i.span,
1212 hir_id,
1213 &sig.decl,
1214 sig.header.coroutine_kind,
1215 body.as_deref(),
1216 attrs,
1217 contract.as_deref(),
1218 );
1219 let (generics, sig) = self.lower_method_sig(
1220 generics,
1221 sig,
1222 i.id,
1223 if is_in_trait_impl { FnDeclKind::Impl } else { FnDeclKind::Inherent },
1224 sig.header.coroutine_kind,
1225 attrs,
1226 );
1227 self.lower_define_opaque(hir_id, &define_opaque);
1228
1229 (*ident, (generics, hir::ImplItemKind::Fn(sig, body_id)))
1230 }
1231 AssocItemKind::Type(TyAlias { ident, generics, after_where_clause, ty, .. }) => {
1232 let mut generics = generics.clone();
1233 add_ty_alias_where_clause(&mut generics, after_where_clause, false);
1234 (
1235 *ident,
1236 self.lower_generics(
1237 &generics,
1238 ImplTraitContext::Disallowed(ImplTraitPosition::Generic),
1239 |this| match ty {
1240 None => {
1241 let guar = this.dcx().span_delayed_bug(
1242 i.span,
1243 "expected to lower associated type, but it was missing",
1244 );
1245 let ty = this.arena.alloc(this.ty(i.span, hir::TyKind::Err(guar)));
1246 hir::ImplItemKind::Type(ty)
1247 }
1248 Some(ty) => {
1249 let ty = this.lower_ty_alloc(
1250 ty,
1251 ImplTraitContext::OpaqueTy {
1252 origin: hir::OpaqueTyOrigin::TyAlias {
1253 parent: this.owner.def_id,
1254 in_assoc_ty: true,
1255 },
1256 },
1257 );
1258 hir::ImplItemKind::Type(ty)
1259 }
1260 },
1261 ),
1262 )
1263 }
1264 AssocItemKind::Delegation(delegation) => {
1265 let delegation_results = self.lower_delegation(delegation);
1266 (
1267 delegation.ident,
1268 (
1269 delegation_results.generics,
1270 hir::ImplItemKind::Fn(delegation_results.sig, delegation_results.body_id),
1271 ),
1272 )
1273 }
1274 AssocItemKind::MacCall(..) | AssocItemKind::DelegationMac(..) => {
1275 {
::core::panicking::panic_fmt(format_args!("macros should have been expanded by now"));
}panic!("macros should have been expanded by now")
1276 }
1277 };
1278
1279 let span = self.lower_span(i.span);
1280 let (effective_ident, impl_kind) = if is_in_trait_impl {
1281 let trait_item_def_id = self
1282 .get_partial_res(i.id)
1283 .and_then(|r| r.expect_full_res().opt_def_id())
1284 .ok_or_else(|| {
1285 self.dcx()
1286 .span_delayed_bug(span, "could not resolve trait item being implemented")
1287 });
1288 let effective_ident = self.check_pin_drop_sugar_impl_item(i, ident, trait_item_def_id);
1289 (effective_ident, ImplItemImplKind::Trait { defaultness, trait_item_def_id })
1290 } else {
1291 (ident, ImplItemImplKind::Inherent { vis_span: self.lower_span(i.vis.span) })
1292 };
1293
1294 let item = hir::ImplItem {
1295 owner_id,
1296 ident: self.lower_ident(effective_ident),
1297 generics,
1298 impl_kind,
1299 kind,
1300 span,
1301 };
1302 self.arena.alloc(item)
1303 }
1304
1305 fn lower_impl_item_ref(&mut self, i: &AssocItem) -> hir::ImplItemId {
1306 hir::ImplItemId { owner_id: self.owner_id(i.id) }
1307 }
1308
1309 fn lower_defaultness(
1310 &self,
1311 d: Defaultness,
1312 has_value: bool,
1313 implicit: impl FnOnce() -> hir::Defaultness,
1314 ) -> (hir::Defaultness, Option<Span>) {
1315 match d {
1316 Defaultness::Implicit => (implicit(), None),
1317 Defaultness::Default(sp) => {
1318 (hir::Defaultness::Default { has_value }, Some(self.lower_span(sp)))
1319 }
1320 Defaultness::Final(sp) => (hir::Defaultness::Final, Some(self.lower_span(sp))),
1321 }
1322 }
1323
1324 fn record_body(
1325 &mut self,
1326 params: &'hir [hir::Param<'hir>],
1327 value: hir::Expr<'hir>,
1328 ) -> hir::BodyId {
1329 let body = hir::Body { params, value: self.arena.alloc(value) };
1330 let id = body.id();
1331 {
match (&id.hir_id.owner, &self.current_hir_id_owner) {
(left_val, right_val) => {
if !(*left_val == *right_val) {
let kind = ::core::panicking::AssertKind::Eq;
::core::panicking::assert_failed(kind, &*left_val,
&*right_val, ::core::option::Option::None);
}
}
}
};assert_eq!(id.hir_id.owner, self.current_hir_id_owner);
1332 self.bodies.push((id.hir_id.local_id, self.arena.alloc(body)));
1333 id
1334 }
1335
1336 pub(super) fn lower_body(
1337 &mut self,
1338 f: impl FnOnce(&mut Self) -> (&'hir [hir::Param<'hir>], hir::Expr<'hir>),
1339 ) -> hir::BodyId {
1340 let prev_coroutine_kind = self.coroutine_kind.take();
1341 let task_context = self.task_context.take();
1342 let (parameters, result) = f(self);
1343 let body_id = self.record_body(parameters, result);
1344 self.task_context = task_context;
1345 self.coroutine_kind = prev_coroutine_kind;
1346 body_id
1347 }
1348
1349 fn lower_param(&mut self, param: &Param) -> hir::Param<'hir> {
1350 let hir_id = self.lower_node_id(param.id);
1351 self.lower_attrs(hir_id, ¶m.attrs, param.span, Target::Param);
1352 hir::Param {
1353 hir_id,
1354 pat: self.lower_pat(¶m.pat),
1355 ty_span: self.lower_span(param.ty.span),
1356 span: self.lower_span(param.span),
1357 }
1358 }
1359
1360 pub(super) fn lower_fn_body(
1361 &mut self,
1362 decl: &FnDecl,
1363 contract: Option<&FnContract>,
1364 body: impl FnOnce(&mut Self) -> hir::Expr<'hir>,
1365 ) -> hir::BodyId {
1366 self.lower_body(|this| {
1367 let params =
1368 this.arena.alloc_from_iter(decl.inputs.iter().map(|x| this.lower_param(x)));
1369
1370 if let Some(contract) = contract {
1372 (params, this.lower_contract(body, contract))
1373 } else {
1374 (params, body(this))
1375 }
1376 })
1377 }
1378
1379 fn lower_fn_body_block(
1380 &mut self,
1381 decl: &FnDecl,
1382 body: &Block,
1383 contract: Option<&FnContract>,
1384 ) -> hir::BodyId {
1385 self.lower_fn_body(decl, contract, |this| this.lower_block_expr(body))
1386 }
1387
1388 pub(super) fn lower_const_body(&mut self, span: Span, expr: Option<&Expr>) -> hir::BodyId {
1389 self.lower_body(|this| {
1390 (
1391 &[],
1392 match expr {
1393 Some(expr) => this.lower_expr_mut(expr),
1394 None => this.expr_err(span, this.dcx().span_delayed_bug(span, "no block")),
1395 },
1396 )
1397 })
1398 }
1399
1400 fn lower_maybe_coroutine_body(
1403 &mut self,
1404 fn_decl_span: Span,
1405 span: Span,
1406 fn_id: hir::HirId,
1407 decl: &FnDecl,
1408 coroutine_kind: Option<CoroutineKind>,
1409 body: Option<&Block>,
1410 attrs: &'hir [hir::Attribute],
1411 contract: Option<&FnContract>,
1412 ) -> hir::BodyId {
1413 let Some(body) = body else {
1414 return self.lower_fn_body(decl, contract, |this| {
1418 if {
{
'done:
{
for i in attrs {
#[allow(unused_imports)]
use rustc_hir::attrs::AttributeKind::*;
let i: &rustc_hir::Attribute = i;
match i {
rustc_hir::Attribute::Parsed(RustcIntrinsic) => {
break 'done Some(());
}
rustc_hir::Attribute::Unparsed(..) =>
{}
#[deny(unreachable_patterns)]
_ => {}
}
}
None
}
}.is_some()
}find_attr!(attrs, RustcIntrinsic) || this.tcx.is_sdylib_interface_build() {
1419 let span = this.lower_span(span);
1420 let empty_block = hir::Block {
1421 hir_id: this.next_id(),
1422 stmts: &[],
1423 expr: None,
1424 rules: hir::BlockCheckMode::DefaultBlock,
1425 span,
1426 targeted_by_break: false,
1427 };
1428 let loop_ = hir::ExprKind::Loop(
1429 this.arena.alloc(empty_block),
1430 None,
1431 hir::LoopSource::Loop,
1432 span,
1433 );
1434 hir::Expr { hir_id: this.next_id(), kind: loop_, span }
1435 } else {
1436 this.expr_err(span, this.dcx().has_errors().unwrap())
1437 }
1438 });
1439 };
1440 let Some(coroutine_kind) = coroutine_kind else {
1441 return self.lower_fn_body_block(decl, body, contract);
1443 };
1444 self.lower_body(|this| {
1446 let (parameters, expr) = this.lower_coroutine_body_with_moved_arguments(
1447 decl,
1448 |this| this.lower_block_expr(body),
1449 fn_decl_span,
1450 body.span,
1451 coroutine_kind,
1452 hir::CoroutineSource::Fn,
1453 );
1454
1455 let hir_id = expr.hir_id;
1457 this.maybe_forward_track_caller(body.span, fn_id, hir_id);
1458
1459 (parameters, expr)
1460 })
1461 }
1462
1463 pub(crate) fn lower_coroutine_body_with_moved_arguments(
1468 &mut self,
1469 decl: &FnDecl,
1470 lower_body: impl FnOnce(&mut LoweringContext<'_, 'hir>) -> hir::Expr<'hir>,
1471 fn_decl_span: Span,
1472 body_span: Span,
1473 coroutine_kind: CoroutineKind,
1474 coroutine_source: hir::CoroutineSource,
1475 ) -> (&'hir [hir::Param<'hir>], hir::Expr<'hir>) {
1476 let mut parameters: Vec<hir::Param<'_>> = Vec::new();
1477 let mut statements: Vec<hir::Stmt<'_>> = Vec::new();
1478
1479 for (index, parameter) in decl.inputs.iter().enumerate() {
1512 let parameter = self.lower_param(parameter);
1513 let span = parameter.pat.span;
1514
1515 let (ident, is_simple_parameter) = match parameter.pat.kind {
1518 hir::PatKind::Binding(hir::BindingMode(ByRef::No, _), _, ident, _) => (ident, true),
1519 hir::PatKind::Binding(_, _, ident, _) => (ident, false),
1523 hir::PatKind::Wild => (Ident::with_dummy_span(rustc_span::kw::Underscore), false),
1524 _ => {
1525 let name = ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("__arg{0}", index))
})format!("__arg{index}");
1527 let ident = Ident::from_str(&name);
1528
1529 (ident, false)
1530 }
1531 };
1532
1533 let desugared_span = self.mark_span_with_reason(DesugaringKind::Async, span, None);
1534
1535 let stmt_attrs = self.attrs.get(¶meter.hir_id.local_id).copied();
1541 let (new_parameter_pat, new_parameter_id) = self.pat_ident(desugared_span, ident);
1542 let new_parameter = hir::Param {
1543 hir_id: parameter.hir_id,
1544 pat: new_parameter_pat,
1545 ty_span: self.lower_span(parameter.ty_span),
1546 span: self.lower_span(parameter.span),
1547 };
1548
1549 if is_simple_parameter {
1550 let expr = self.expr_ident(desugared_span, ident, new_parameter_id);
1554 let stmt = self.stmt_let_pat(
1555 stmt_attrs,
1556 desugared_span,
1557 Some(expr),
1558 parameter.pat,
1559 hir::LocalSource::AsyncFn,
1560 );
1561 statements.push(stmt);
1562 } else {
1563 let (move_pat, move_id) =
1579 self.pat_ident_binding_mode(desugared_span, ident, hir::BindingMode::MUT);
1580 let move_expr = self.expr_ident(desugared_span, ident, new_parameter_id);
1581 let move_stmt = self.stmt_let_pat(
1582 None,
1583 desugared_span,
1584 Some(move_expr),
1585 move_pat,
1586 hir::LocalSource::AsyncFn,
1587 );
1588
1589 let pattern_expr = self.expr_ident(desugared_span, ident, move_id);
1592 let pattern_stmt = self.stmt_let_pat(
1593 stmt_attrs,
1594 desugared_span,
1595 Some(pattern_expr),
1596 parameter.pat,
1597 hir::LocalSource::AsyncFn,
1598 );
1599
1600 statements.push(move_stmt);
1601 statements.push(pattern_stmt);
1602 };
1603
1604 parameters.push(new_parameter);
1605 }
1606
1607 let mkbody = |this: &mut LoweringContext<'_, 'hir>| {
1608 let user_body = lower_body(this);
1610
1611 let desugared_span =
1613 this.mark_span_with_reason(DesugaringKind::Async, user_body.span, None);
1614 let user_body = this.expr_drop_temps(desugared_span, this.arena.alloc(user_body));
1615
1616 let body = this.block_all(
1626 desugared_span,
1627 this.arena.alloc_from_iter(statements),
1628 Some(user_body),
1629 );
1630
1631 this.expr_block(body)
1632 };
1633 let desugaring_kind = match coroutine_kind {
1634 CoroutineKind::Async { .. } => hir::CoroutineDesugaring::Async,
1635 CoroutineKind::Gen { .. } => hir::CoroutineDesugaring::Gen,
1636 CoroutineKind::AsyncGen { .. } => hir::CoroutineDesugaring::AsyncGen,
1637 };
1638 let closure_id = coroutine_kind.closure_id();
1639
1640 let coroutine_expr = self.make_desugared_coroutine_expr(
1641 CaptureBy::Ref,
1646 closure_id,
1647 None,
1648 fn_decl_span,
1649 body_span,
1650 desugaring_kind,
1651 coroutine_source,
1652 mkbody,
1653 );
1654
1655 let expr = hir::Expr {
1656 hir_id: self.lower_node_id(closure_id),
1657 kind: coroutine_expr,
1658 span: self.lower_span(body_span),
1659 };
1660
1661 (self.arena.alloc_from_iter(parameters), expr)
1662 }
1663
1664 fn lower_method_sig(
1665 &mut self,
1666 generics: &Generics,
1667 sig: &FnSig,
1668 id: NodeId,
1669 kind: FnDeclKind,
1670 coroutine_kind: Option<CoroutineKind>,
1671 attrs: &[hir::Attribute],
1672 ) -> (&'hir hir::Generics<'hir>, hir::FnSig<'hir>) {
1673 let header = self.lower_fn_header(sig.header, hir::Safety::Safe, attrs);
1674 let itctx = ImplTraitContext::Universal;
1675 let (generics, decl) = self.lower_generics(generics, itctx, |this| {
1676 this.lower_fn_decl(&sig.decl, id, sig.span, kind, coroutine_kind)
1677 });
1678 (generics, hir::FnSig { header, decl, span: self.lower_span(sig.span) })
1679 }
1680
1681 pub(super) fn lower_fn_header(
1682 &mut self,
1683 h: FnHeader,
1684 default_safety: hir::Safety,
1685 attrs: &[hir::Attribute],
1686 ) -> hir::FnHeader {
1687 let asyncness = if let Some(CoroutineKind::Async { span, .. }) = h.coroutine_kind {
1688 hir::IsAsync::Async(self.lower_span(span))
1689 } else {
1690 hir::IsAsync::NotAsync
1691 };
1692
1693 let safety = self.lower_safety(h.safety, default_safety);
1694
1695 let safety = if {
{
'done:
{
for i in attrs {
#[allow(unused_imports)]
use rustc_hir::attrs::AttributeKind::*;
let i: &rustc_hir::Attribute = i;
match i {
rustc_hir::Attribute::Parsed(TargetFeature {
was_forced: false, .. }) => {
break 'done Some(());
}
rustc_hir::Attribute::Unparsed(..) =>
{}
#[deny(unreachable_patterns)]
_ => {}
}
}
None
}
}.is_some()
}find_attr!(attrs, TargetFeature { was_forced: false, .. })
1697 && safety.is_safe()
1698 && !self.tcx.sess.target.is_like_wasm
1699 {
1700 hir::HeaderSafety::SafeTargetFeatures
1701 } else {
1702 safety.into()
1703 };
1704
1705 let mut constness = self.lower_constness(h.constness);
1706 if let Some(&attr_span) = {
'done:
{
for i in attrs {
#[allow(unused_imports)]
use rustc_hir::attrs::AttributeKind::*;
let i: &rustc_hir::Attribute = i;
match i {
rustc_hir::Attribute::Parsed(RustcComptime(span)) => {
break 'done Some(span);
}
rustc_hir::Attribute::Unparsed(..) =>
{}
#[deny(unreachable_patterns)]
_ => {}
}
}
None
}
}find_attr!(attrs, RustcComptime(span) => span) {
1707 match std::mem::replace(&mut constness, rustc_hir::Constness::Const { always: true }) {
1708 rustc_hir::Constness::Const { always: true } => {
1709 {
::core::panicking::panic_fmt(format_args!("internal error: entered unreachable code: {0}",
format_args!("lower_constness cannot produce comptime")));
}unreachable!("lower_constness cannot produce comptime")
1710 }
1711 rustc_hir::Constness::Const { always: false } => {
1713 let Const::Yes(span) = h.constness else { ::core::panicking::panic("internal error: entered unreachable code")unreachable!() };
1714 self.dcx().emit_err(ConstComptimeFn { span, attr_span });
1715 }
1716 rustc_hir::Constness::NotConst => {}
1718 }
1719 }
1720
1721 hir::FnHeader { safety, asyncness, constness, abi: self.lower_extern(h.ext) }
1722 }
1723
1724 pub(super) fn lower_abi(&mut self, abi_str: StrLit) -> ExternAbi {
1725 let ast::StrLit { symbol_unescaped, span, .. } = abi_str;
1726 let extern_abi = symbol_unescaped.as_str().parse().unwrap_or_else(|_| {
1727 self.error_on_invalid_abi(abi_str);
1728 ExternAbi::Rust
1729 });
1730 let tcx = self.tcx;
1731
1732 if !tcx.sess.target.is_abi_supported(extern_abi) {
1734 let mut err = {
tcx.dcx().struct_span_err(span,
::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0} is not a supported ABI for the current target",
extern_abi))
})).with_code(E0570)
}struct_span_code_err!(
1735 tcx.dcx(),
1736 span,
1737 E0570,
1738 "{extern_abi} is not a supported ABI for the current target",
1739 );
1740
1741 if let ExternAbi::Stdcall { unwind } = extern_abi {
1742 let c_abi = ExternAbi::C { unwind };
1743 let system_abi = ExternAbi::System { unwind };
1744 err.help(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("if you need `extern {0}` on win32 and `extern {1}` everywhere else, use `extern {2}`",
extern_abi, c_abi, system_abi))
})format!("if you need `extern {extern_abi}` on win32 and `extern {c_abi}` everywhere else, \
1745 use `extern {system_abi}`"
1746 ));
1747 }
1748 err.emit();
1749 }
1750 gate_unstable_abi(tcx.sess, tcx.features(), span, extern_abi);
1753 extern_abi
1754 }
1755
1756 pub(super) fn lower_extern(&mut self, ext: Extern) -> ExternAbi {
1757 match ext {
1758 Extern::None => ExternAbi::Rust,
1759 Extern::Implicit(_) => ExternAbi::FALLBACK,
1760 Extern::Explicit(abi, _) => self.lower_abi(abi),
1761 }
1762 }
1763
1764 fn error_on_invalid_abi(&self, abi: StrLit) {
1765 let abi_names = enabled_names(self.tcx.features(), abi.span)
1766 .iter()
1767 .map(|s| Symbol::intern(s))
1768 .collect::<Vec<_>>();
1769 let suggested_name = find_best_match_for_name(&abi_names, abi.symbol_unescaped, None);
1770 self.dcx().emit_err(InvalidAbi {
1771 abi: abi.symbol_unescaped,
1772 span: abi.span,
1773 suggestion: suggested_name.map(|suggested_name| InvalidAbiSuggestion {
1774 span: abi.span,
1775 suggestion: suggested_name.to_string(),
1776 }),
1777 command: "rustc --print=calling-conventions".to_string(),
1778 });
1779 }
1780
1781 pub(super) fn lower_constness(&mut self, c: Const) -> hir::Constness {
1782 match c {
1783 Const::Yes(_) => hir::Constness::Const { always: false },
1784 Const::No => hir::Constness::NotConst,
1785 }
1786 }
1787
1788 pub(super) fn lower_safety(&self, s: Safety, default: hir::Safety) -> hir::Safety {
1789 match s {
1790 Safety::Unsafe(_) => hir::Safety::Unsafe,
1791 Safety::Default => default,
1792 Safety::Safe(_) => hir::Safety::Safe,
1793 }
1794 }
1795
1796 fn lower_restriction_kind(&mut self, kind: &RestrictionKind) -> hir::RestrictionKind<'hir> {
1797 match kind {
1798 RestrictionKind::Unrestricted => hir::RestrictionKind::Unrestricted,
1799 RestrictionKind::Restricted { path, id, shorthand: _ } => {
1800 let res = self.get_partial_res(*id);
1801 if let Some(did) = res.and_then(|res| res.expect_full_res().opt_def_id()) {
1802 hir::RestrictionKind::Restricted(self.arena.alloc(hir::Path {
1803 res: did,
1804 segments: self.arena.alloc_from_iter(path.segments.iter().map(|segment| {
1805 self.lower_path_segment(
1806 path.span,
1807 segment,
1808 ParamMode::Explicit,
1809 GenericArgsMode::Err,
1810 ImplTraitContext::Disallowed(ImplTraitPosition::Path),
1811 None,
1812 )
1813 })),
1814 span: self.lower_span(path.span),
1815 }))
1816 } else {
1817 self.dcx().span_delayed_bug(path.span, "should have errored in resolve");
1818 hir::RestrictionKind::Unrestricted
1819 }
1820 }
1821 }
1822 }
1823
1824 pub(super) fn lower_impl_restriction(
1825 &mut self,
1826 r: &ImplRestriction,
1827 ) -> &'hir hir::ImplRestriction<'hir> {
1828 let kind = self.lower_restriction_kind(&r.kind);
1829 self.arena.alloc(hir::ImplRestriction { kind, span: self.lower_span(r.span) })
1830 }
1831
1832 pub(super) fn lower_mut_restriction(
1833 &mut self,
1834 r: &MutRestriction,
1835 ) -> &'hir hir::MutRestriction<'hir> {
1836 let kind = self.lower_restriction_kind(&r.kind);
1837 self.arena.alloc(hir::MutRestriction { kind, span: self.lower_span(r.span) })
1838 }
1839
1840 #[allow(clippy :: suspicious_else_formatting)]
{
let __tracing_attr_span;
let __tracing_attr_guard;
if ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() ||
{ false } {
__tracing_attr_span =
{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("lower_generics",
"rustc_ast_lowering::item", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_ast_lowering/src/item.rs"),
::tracing_core::__macro_support::Option::Some(1842u32),
::tracing_core::__macro_support::Option::Some("rustc_ast_lowering::item"),
::tracing_core::field::FieldSet::new(&["generics", "itctx"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::SPAN)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let mut interest = ::tracing::subscriber::Interest::never();
if ::tracing::Level::DEBUG <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{ interest = __CALLSITE.interest(); !interest.is_never() }
&&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest) {
let meta = __CALLSITE.metadata();
::tracing::Span::new(meta,
&{
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = meta.fields().iter();
meta.fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&::tracing::field::debug(&generics)
as &dyn Value)),
(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&::tracing::field::debug(&itctx)
as &dyn Value))])
})
} else {
let span =
::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
{};
span
}
};
__tracing_attr_guard = __tracing_attr_span.enter();
}
#[warn(clippy :: suspicious_else_formatting)]
{
#[allow(unknown_lints, unreachable_code, clippy ::
diverging_sub_expression, clippy :: empty_loop, clippy ::
let_unit_value, clippy :: let_with_type_underscore, clippy ::
needless_return, clippy :: unreachable)]
if false {
let __tracing_attr_fake_return: (&'hir hir::Generics<'hir>, T) =
loop {};
return __tracing_attr_fake_return;
}
{
if !self.impl_trait_defs.is_empty() {
::core::panicking::panic("assertion failed: self.impl_trait_defs.is_empty()")
};
if !self.impl_trait_bounds.is_empty() {
::core::panicking::panic("assertion failed: self.impl_trait_bounds.is_empty()")
};
let mut predicates: SmallVec<[hir::WherePredicate<'hir>; 4]> =
SmallVec::new();
let mut dedup_map: IndexMap<LocalDefId, _> = Default::default();
predicates.extend(generics.params.iter().filter_map(|param|
{
self.lower_generic_bound_predicate(param.ident, param.id,
¶m.kind, ¶m.bounds, param.colon_span, generics.span,
RelaxedBoundPolicy::Allowed(dedup_map.entry(self.local_def_id(param.id)).or_default()),
itctx, PredicateOrigin::GenericParam)
}));
predicates.extend(generics.where_clause.predicates.iter().map(|predicate|
{
self.lower_where_predicate(predicate, &generics.params,
&mut dedup_map)
}));
let mut params: SmallVec<[hir::GenericParam<'hir>; 4]> =
self.lower_generic_params_mut(&generics.params,
hir::GenericParamSource::Generics).collect();
let extra_lifetimes =
self.resolver.extra_lifetime_params(self.owner.id);
params.extend(extra_lifetimes.into_iter().map(|&(ident, node_id,
kind)|
{
self.lifetime_res_to_generic_param(ident, node_id, kind,
hir::GenericParamSource::Generics)
}));
let has_where_clause_predicates =
!generics.where_clause.predicates.is_empty();
let where_clause_span =
self.lower_span(generics.where_clause.span);
let span = self.lower_span(generics.span);
let res = f(self);
let impl_trait_defs = std::mem::take(&mut self.impl_trait_defs);
params.extend(impl_trait_defs.into_iter());
let impl_trait_bounds =
std::mem::take(&mut self.impl_trait_bounds);
predicates.extend(impl_trait_bounds.into_iter());
let lowered_generics =
self.arena.alloc(hir::Generics {
params: self.arena.alloc_from_iter(params),
predicates: self.arena.alloc_from_iter(predicates),
has_where_clause_predicates,
where_clause_span,
span,
});
(lowered_generics, res)
}
}
}#[instrument(level = "debug", skip(self, f))]
1843 fn lower_generics<T>(
1844 &mut self,
1845 generics: &Generics,
1846 itctx: ImplTraitContext,
1847 f: impl FnOnce(&mut Self) -> T,
1848 ) -> (&'hir hir::Generics<'hir>, T) {
1849 assert!(self.impl_trait_defs.is_empty());
1850 assert!(self.impl_trait_bounds.is_empty());
1851
1852 let mut predicates: SmallVec<[hir::WherePredicate<'hir>; 4]> = SmallVec::new();
1853 let mut dedup_map: IndexMap<LocalDefId, _> = Default::default();
1856 predicates.extend(generics.params.iter().filter_map(|param| {
1857 self.lower_generic_bound_predicate(
1858 param.ident,
1859 param.id,
1860 ¶m.kind,
1861 ¶m.bounds,
1862 param.colon_span,
1863 generics.span,
1864 RelaxedBoundPolicy::Allowed(
1865 dedup_map.entry(self.local_def_id(param.id)).or_default(),
1866 ),
1867 itctx,
1868 PredicateOrigin::GenericParam,
1869 )
1870 }));
1871 predicates.extend(generics.where_clause.predicates.iter().map(|predicate| {
1872 self.lower_where_predicate(predicate, &generics.params, &mut dedup_map)
1873 }));
1874
1875 let mut params: SmallVec<[hir::GenericParam<'hir>; 4]> = self
1876 .lower_generic_params_mut(&generics.params, hir::GenericParamSource::Generics)
1877 .collect();
1878
1879 let extra_lifetimes = self.resolver.extra_lifetime_params(self.owner.id);
1881 params.extend(extra_lifetimes.into_iter().map(|&(ident, node_id, kind)| {
1882 self.lifetime_res_to_generic_param(
1883 ident,
1884 node_id,
1885 kind,
1886 hir::GenericParamSource::Generics,
1887 )
1888 }));
1889
1890 let has_where_clause_predicates = !generics.where_clause.predicates.is_empty();
1891 let where_clause_span = self.lower_span(generics.where_clause.span);
1892 let span = self.lower_span(generics.span);
1893 let res = f(self);
1894
1895 let impl_trait_defs = std::mem::take(&mut self.impl_trait_defs);
1896 params.extend(impl_trait_defs.into_iter());
1897
1898 let impl_trait_bounds = std::mem::take(&mut self.impl_trait_bounds);
1899 predicates.extend(impl_trait_bounds.into_iter());
1900
1901 let lowered_generics = self.arena.alloc(hir::Generics {
1902 params: self.arena.alloc_from_iter(params),
1903 predicates: self.arena.alloc_from_iter(predicates),
1904 has_where_clause_predicates,
1905 where_clause_span,
1906 span,
1907 });
1908
1909 (lowered_generics, res)
1910 }
1911
1912 pub(super) fn lower_define_opaque(
1913 &mut self,
1914 hir_id: HirId,
1915 define_opaque: &Option<ThinVec<(NodeId, Path)>>,
1916 ) {
1917 {
match (&self.define_opaque, &None) {
(left_val, right_val) => {
if !(*left_val == *right_val) {
let kind = ::core::panicking::AssertKind::Eq;
::core::panicking::assert_failed(kind, &*left_val,
&*right_val, ::core::option::Option::None);
}
}
}
};assert_eq!(self.define_opaque, None);
1918 if !hir_id.is_owner() {
::core::panicking::panic("assertion failed: hir_id.is_owner()")
};assert!(hir_id.is_owner());
1919 let Some(define_opaque) = define_opaque.as_ref() else {
1920 return;
1921 };
1922 let define_opaque = define_opaque.iter().filter_map(|(id, path)| {
1923 let res = self.get_partial_res(*id);
1924 let Some(did) = res.and_then(|res| res.expect_full_res().opt_def_id()) else {
1925 self.dcx().span_delayed_bug(path.span, "should have errored in resolve");
1926 return None;
1927 };
1928 let Some(did) = did.as_local() else {
1929 self.dcx().span_err(
1930 path.span,
1931 "only opaque types defined in the local crate can be defined",
1932 );
1933 return None;
1934 };
1935 Some((self.lower_span(path.span), did))
1936 });
1937 let define_opaque = self.arena.alloc_from_iter(define_opaque);
1938 self.define_opaque = Some(define_opaque);
1939 }
1940
1941 pub(super) fn lower_generic_bound_predicate(
1942 &mut self,
1943 ident: Ident,
1944 id: NodeId,
1945 kind: &GenericParamKind,
1946 bounds: &[GenericBound],
1947 colon_span: Option<Span>,
1948 parent_span: Span,
1949 rbp: RelaxedBoundPolicy<'_>,
1950 itctx: ImplTraitContext,
1951 origin: PredicateOrigin,
1952 ) -> Option<hir::WherePredicate<'hir>> {
1953 if bounds.is_empty() {
1955 return None;
1956 }
1957
1958 let bounds = self.lower_param_bounds(bounds, rbp, itctx);
1959
1960 let param_span = ident.span;
1961
1962 let span_start = colon_span.unwrap_or_else(|| param_span.shrink_to_hi());
1964 let span = bounds.iter().fold(span_start, |span_accum, bound| {
1965 match bound.span().find_ancestor_inside(parent_span) {
1966 Some(bound_span) => span_accum.to(bound_span),
1967 None => span_accum,
1968 }
1969 });
1970 let span = self.lower_span(span);
1971 let hir_id = self.next_id();
1972 let kind = self.arena.alloc(match kind {
1973 GenericParamKind::Const { .. } => return None,
1974 GenericParamKind::Type { .. } => {
1975 let def_id = self.local_def_id(id).to_def_id();
1976 let hir_id = self.next_id();
1977 let res = Res::Def(DefKind::TyParam, def_id);
1978 let ident = self.lower_ident(ident);
1979 let ty_path = self.arena.alloc(hir::Path {
1980 span: self.lower_span(param_span),
1981 res,
1982 segments: self
1983 .arena
1984 .alloc_from_iter([hir::PathSegment::new(ident, hir_id, res)]),
1985 });
1986 let ty_id = self.next_id();
1987 let bounded_ty =
1988 self.ty_path(ty_id, param_span, hir::QPath::Resolved(None, ty_path));
1989 hir::WherePredicateKind::BoundPredicate(hir::WhereBoundPredicate {
1990 bounded_ty: self.arena.alloc(bounded_ty),
1991 bounds,
1992 bound_generic_params: &[],
1993 origin,
1994 })
1995 }
1996 GenericParamKind::Lifetime => {
1997 let lt_id = self.next_node_id();
1998 let lifetime =
1999 self.new_named_lifetime(id, lt_id, ident, LifetimeSource::Other, ident.into());
2000 hir::WherePredicateKind::RegionPredicate(hir::WhereRegionPredicate {
2001 lifetime,
2002 bounds,
2003 in_where_clause: false,
2004 })
2005 }
2006 });
2007 Some(hir::WherePredicate { hir_id, span, kind })
2008 }
2009
2010 fn lower_where_predicate(
2011 &mut self,
2012 pred: &WherePredicate,
2013 params: &[ast::GenericParam],
2014 dedup_map: &mut IndexMap<LocalDefId, IndexMap<DefId, Span>>,
2015 ) -> hir::WherePredicate<'hir> {
2016 let hir_id = self.lower_node_id(pred.id);
2017 let span = self.lower_span(pred.span);
2018 self.lower_attrs(hir_id, &pred.attrs, span, Target::WherePredicate);
2019 let kind = self.arena.alloc(match &pred.kind {
2020 WherePredicateKind::BoundPredicate(WhereBoundPredicate {
2021 bound_generic_params,
2022 bounded_ty,
2023 bounds,
2024 }) => {
2025 let rbp = if bound_generic_params.is_empty()
2026 && let Some(res) =
2027 self.get_partial_res(bounded_ty.id).and_then(|r| r.full_res())
2028 && let Res::Def(DefKind::TyParam, def_id) = res
2029 && params.iter().any(|p| def_id == self.local_def_id(p.id).to_def_id())
2030 {
2031 RelaxedBoundPolicy::Allowed(dedup_map.entry(def_id.expect_local()).or_default())
2032 } else {
2033 RelaxedBoundPolicy::Forbidden(RelaxedBoundForbiddenReason::WhereBound)
2034 };
2035 hir::WherePredicateKind::BoundPredicate(hir::WhereBoundPredicate {
2036 bound_generic_params: self.lower_generic_params(
2037 bound_generic_params,
2038 hir::GenericParamSource::Binder,
2039 ),
2040 bounded_ty: self.lower_ty_alloc(
2041 bounded_ty,
2042 ImplTraitContext::Disallowed(ImplTraitPosition::Bound),
2043 ),
2044 bounds: self.lower_param_bounds(
2045 bounds,
2046 rbp,
2047 ImplTraitContext::Disallowed(ImplTraitPosition::Bound),
2048 ),
2049 origin: PredicateOrigin::WhereClause,
2050 })
2051 }
2052 WherePredicateKind::RegionPredicate(WhereRegionPredicate { lifetime, bounds }) => {
2053 hir::WherePredicateKind::RegionPredicate(hir::WhereRegionPredicate {
2054 lifetime: self.lower_lifetime(
2055 lifetime,
2056 LifetimeSource::Other,
2057 lifetime.ident.into(),
2058 ),
2059 bounds: self.lower_param_bounds(
2060 bounds,
2061 RelaxedBoundPolicy::Allowed(&mut Default::default()),
2062 ImplTraitContext::Disallowed(ImplTraitPosition::Bound),
2063 ),
2064 in_where_clause: true,
2065 })
2066 }
2067 });
2068 hir::WherePredicate { hir_id, span, kind }
2069 }
2070}