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