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