]> git.proxmox.com Git - rustc.git/blame - compiler/rustc_ast_lowering/src/item.rs
New upstream version 1.67.1+dfsg1
[rustc.git] / compiler / rustc_ast_lowering / src / item.rs
CommitLineData
2b03887a 1use super::errors::{InvalidAbi, InvalidAbiSuggestion, MisplacedRelaxTraitBound};
923072b8 2use super::ResolverAstLoweringExt;
f2b60f7d 3use super::{Arena, AstOwner, ImplTraitContext, ImplTraitPosition};
064997fb 4use super::{FnDeclKind, LoweringContext, ParamMode};
dfeec247 5
ba9703b0 6use rustc_ast::ptr::P;
5e7ed085 7use rustc_ast::visit::AssocCtxt;
3dfed10e 8use rustc_ast::*;
5e7ed085 9use rustc_data_structures::sorted_map::SortedMap;
dfeec247
XL
10use rustc_hir as hir;
11use rustc_hir::def::{DefKind, Res};
5e7ed085 12use rustc_hir::def_id::{LocalDefId, CRATE_DEF_ID};
04454e1e 13use rustc_hir::PredicateOrigin;
5e7ed085 14use rustc_index::vec::{Idx, IndexVec};
064997fb 15use rustc_middle::ty::{DefIdTree, ResolverAstLowering, TyCtxt};
2b03887a 16use rustc_span::lev_distance::find_best_match_for_name;
04454e1e 17use rustc_span::source_map::DesugaringKind;
f9f354fc 18use rustc_span::symbol::{kw, sym, Ident};
2b03887a 19use rustc_span::{Span, Symbol};
60c5eb7d 20use rustc_target::spec::abi;
dfeec247 21use smallvec::{smallvec, SmallVec};
487cf647 22use thin_vec::ThinVec;
6a06907d 23
5e7ed085 24pub(super) struct ItemLowerer<'a, 'hir> {
064997fb 25 pub(super) tcx: TyCtxt<'hir>,
923072b8 26 pub(super) resolver: &'a mut ResolverAstLowering,
f2b60f7d 27 pub(super) ast_arena: &'a Arena<'static>,
5e7ed085
FG
28 pub(super) ast_index: &'a IndexVec<LocalDefId, AstOwner<'a>>,
29 pub(super) owners: &'a mut IndexVec<LocalDefId, hir::MaybeOwner<&'hir hir::OwnerInfo<'hir>>>,
416331ca
XL
30}
31
5e7ed085
FG
32/// When we have a ty alias we *may* have two where clauses. To give the best diagnostics, we set the span
33/// to the where clause that is preferred, if it exists. Otherwise, it sets the span to the other where
34/// clause if it exists.
35fn add_ty_alias_where_clause(
36 generics: &mut ast::Generics,
37 mut where_clauses: (TyAliasWhereClause, TyAliasWhereClause),
38 prefer_first: bool,
39) {
40 if !prefer_first {
41 where_clauses = (where_clauses.1, where_clauses.0);
42 }
43 if where_clauses.0.0 || !where_clauses.1.0 {
44 generics.where_clause.has_where_token = where_clauses.0.0;
45 generics.where_clause.span = where_clauses.0.1;
46 } else {
47 generics.where_clause.has_where_token = where_clauses.1.0;
48 generics.where_clause.span = where_clauses.1.1;
416331ca
XL
49 }
50}
51
5e7ed085
FG
52impl<'a, 'hir> ItemLowerer<'a, 'hir> {
53 fn with_lctx(
54 &mut self,
55 owner: NodeId,
56 f: impl FnOnce(&mut LoweringContext<'_, 'hir>) -> hir::OwnerNode<'hir>,
57 ) {
58 let mut lctx = LoweringContext {
59 // Pseudo-globals.
064997fb 60 tcx: self.tcx,
5e7ed085 61 resolver: self.resolver,
064997fb 62 arena: self.tcx.hir_arena,
f2b60f7d 63 ast_arena: self.ast_arena,
5e7ed085
FG
64
65 // HirId handling.
66 bodies: Vec::new(),
67 attrs: SortedMap::default(),
487cf647 68 children: Vec::default(),
2b03887a 69 current_hir_id_owner: hir::CRATE_OWNER_ID,
5e7ed085
FG
70 item_local_id_counter: hir::ItemLocalId::new(0),
71 node_id_to_local_id: Default::default(),
72 local_id_to_def_id: SortedMap::new(),
73 trait_map: Default::default(),
74
75 // Lowering state.
76 catch_scope: None,
77 loop_scope: None,
78 is_in_loop_condition: false,
79 is_in_trait_impl: false,
80 is_in_dyn_type: false,
5e7ed085
FG
81 generator_kind: None,
82 task_context: None,
83 current_item: None,
923072b8
FG
84 impl_trait_defs: Vec::new(),
85 impl_trait_bounds: Vec::new(),
04454e1e 86 allow_try_trait: Some([sym::try_trait_v2, sym::yeet_desugar_details][..].into()),
487cf647 87 allow_gen_future: Some([sym::gen_future, sym::closure_track_caller][..].into()),
5e7ed085 88 allow_into_future: Some([sym::into_future][..].into()),
f2b60f7d 89 generics_def_id_map: Default::default(),
5e7ed085
FG
90 };
91 lctx.with_hir_id_owner(owner, |lctx| f(lctx));
3c0e092e 92
5e7ed085
FG
93 for (def_id, info) in lctx.children {
94 self.owners.ensure_contains_elem(def_id, || hir::MaybeOwner::Phantom);
95 debug_assert!(matches!(self.owners[def_id], hir::MaybeOwner::Phantom));
96 self.owners[def_id] = info;
97 }
416331ca
XL
98 }
99
5e7ed085
FG
100 pub(super) fn lower_node(
101 &mut self,
102 def_id: LocalDefId,
103 ) -> hir::MaybeOwner<&'hir hir::OwnerInfo<'hir>> {
104 self.owners.ensure_contains_elem(def_id, || hir::MaybeOwner::Phantom);
105 if let hir::MaybeOwner::Phantom = self.owners[def_id] {
106 let node = self.ast_index[def_id];
107 match node {
108 AstOwner::NonOwner => {}
109 AstOwner::Crate(c) => self.lower_crate(c),
110 AstOwner::Item(item) => self.lower_item(item),
111 AstOwner::AssocItem(item, ctxt) => self.lower_assoc_item(item, ctxt),
112 AstOwner::ForeignItem(item) => self.lower_foreign_item(item),
3dfed10e 113 }
3dfed10e 114 }
3dfed10e 115
5e7ed085 116 self.owners[def_id]
416331ca 117 }
fc512014 118
923072b8 119 #[instrument(level = "debug", skip(self, c))]
5e7ed085 120 fn lower_crate(&mut self, c: &Crate) {
923072b8 121 debug_assert_eq!(self.resolver.node_id_to_def_id[&CRATE_NODE_ID], CRATE_DEF_ID);
5e7ed085 122 self.with_lctx(CRATE_NODE_ID, |lctx| {
04454e1e 123 let module = lctx.lower_mod(&c.items, &c.spans);
5e7ed085 124 lctx.lower_attrs(hir::CRATE_HIR_ID, &c.attrs);
f2b60f7d 125 hir::OwnerNode::Crate(module)
5e7ed085 126 })
fc512014 127 }
416331ca 128
923072b8 129 #[instrument(level = "debug", skip(self))]
5e7ed085
FG
130 fn lower_item(&mut self, item: &Item) {
131 self.with_lctx(item.id, |lctx| hir::OwnerNode::Item(lctx.lower_item(item)))
416331ca
XL
132 }
133
5e7ed085 134 fn lower_assoc_item(&mut self, item: &AssocItem, ctxt: AssocCtxt) {
923072b8 135 let def_id = self.resolver.node_id_to_def_id[&item.id];
e1599b0c 136
064997fb 137 let parent_id = self.tcx.local_parent(def_id);
04454e1e 138 let parent_hir = self.lower_node(parent_id).unwrap();
5e7ed085
FG
139 self.with_lctx(item.id, |lctx| {
140 // Evaluate with the lifetimes in `params` in-scope.
141 // This is used to track which lifetimes have already been defined,
142 // and which need to be replicated when lowering an async fn.
04454e1e 143 match parent_hir.node().expect_item().kind {
487cf647 144 hir::ItemKind::Impl(hir::Impl { of_trait, .. }) => {
5e7ed085 145 lctx.is_in_trait_impl = of_trait.is_some();
5e7ed085
FG
146 }
147 _ => {}
148 };
e1599b0c 149
5e7ed085
FG
150 match ctxt {
151 AssocCtxt::Trait => hir::OwnerNode::TraitItem(lctx.lower_trait_item(item)),
152 AssocCtxt::Impl => hir::OwnerNode::ImplItem(lctx.lower_impl_item(item)),
153 }
154 })
155 }
e1599b0c 156
5e7ed085
FG
157 fn lower_foreign_item(&mut self, item: &ForeignItem) {
158 self.with_lctx(item.id, |lctx| hir::OwnerNode::ForeignItem(lctx.lower_foreign_item(item)))
e1599b0c 159 }
5e7ed085 160}
e1599b0c 161
5e7ed085 162impl<'hir> LoweringContext<'_, 'hir> {
f2b60f7d
FG
163 pub(super) fn lower_mod(
164 &mut self,
165 items: &[P<Item>],
166 spans: &ModSpans,
167 ) -> &'hir hir::Mod<'hir> {
168 self.arena.alloc(hir::Mod {
04454e1e
FG
169 spans: hir::ModSpans {
170 inner_span: self.lower_span(spans.inner_span),
171 inject_use_span: self.lower_span(spans.inject_use_span),
172 },
c295e0f8 173 item_ids: self.arena.alloc_from_iter(items.iter().flat_map(|x| self.lower_item_ref(x))),
f2b60f7d 174 })
416331ca
XL
175 }
176
c295e0f8 177 pub(super) fn lower_item_ref(&mut self, i: &Item) -> SmallVec<[hir::ItemId; 1]> {
2b03887a
FG
178 let mut node_ids =
179 smallvec![hir::ItemId { owner_id: hir::OwnerId { def_id: self.local_def_id(i.id) } }];
487cf647
FG
180 if let ItemKind::Use(use_tree) = &i.kind {
181 self.lower_item_id_use_tree(use_tree, &mut node_ids);
c295e0f8 182 }
dfeec247 183 node_ids
416331ca
XL
184 }
185
487cf647
FG
186 fn lower_item_id_use_tree(&mut self, tree: &UseTree, vec: &mut SmallVec<[hir::ItemId; 1]>) {
187 match &tree.kind {
188 UseTreeKind::Nested(nested_vec) => {
dfeec247 189 for &(ref nested, id) in nested_vec {
2b03887a
FG
190 vec.push(hir::ItemId {
191 owner_id: hir::OwnerId { def_id: self.local_def_id(id) },
192 });
487cf647 193 self.lower_item_id_use_tree(nested, vec);
416331ca 194 }
dfeec247 195 }
487cf647 196 UseTreeKind::Simple(..) | UseTreeKind::Glob => {}
416331ca
XL
197 }
198 }
199
c295e0f8 200 fn lower_item(&mut self, i: &Item) -> &'hir hir::Item<'hir> {
416331ca 201 let mut ident = i.ident;
04454e1e 202 let vis_span = self.lower_span(i.vis.span);
6a06907d
XL
203 let hir_id = self.lower_node_id(i.id);
204 let attrs = self.lower_attrs(hir_id, &i.attrs);
04454e1e 205 let kind = self.lower_item_kind(i.span, i.id, hir_id, &mut ident, attrs, vis_span, &i.kind);
c295e0f8 206 let item = hir::Item {
2b03887a 207 owner_id: hir_id.expect_owner(),
94222f64
XL
208 ident: self.lower_ident(ident),
209 kind,
04454e1e 210 vis_span,
94222f64 211 span: self.lower_span(i.span),
c295e0f8
XL
212 };
213 self.arena.alloc(item)
416331ca
XL
214 }
215
216 fn lower_item_kind(
217 &mut self,
dfeec247 218 span: Span,
416331ca 219 id: NodeId,
6a06907d 220 hir_id: hir::HirId,
416331ca 221 ident: &mut Ident,
6a06907d 222 attrs: Option<&'hir [Attribute]>,
04454e1e 223 vis_span: Span,
416331ca 224 i: &ItemKind,
dfeec247 225 ) -> hir::ItemKind<'hir> {
487cf647
FG
226 match i {
227 ItemKind::ExternCrate(orig_name) => hir::ItemKind::ExternCrate(*orig_name),
228 ItemKind::Use(use_tree) => {
416331ca 229 // Start with an empty prefix.
487cf647 230 let prefix = Path { segments: ThinVec::new(), span: use_tree.span, tokens: None };
416331ca 231
04454e1e 232 self.lower_use_tree(use_tree, &prefix, id, vis_span, ident, attrs)
416331ca 233 }
487cf647 234 ItemKind::Static(t, m, e) => {
74b04a01 235 let (ty, body_id) = self.lower_const_item(t, span, e.as_deref());
487cf647 236 hir::ItemKind::Static(ty, *m, body_id)
416331ca 237 }
487cf647 238 ItemKind::Const(_, t, e) => {
74b04a01
XL
239 let (ty, body_id) = self.lower_const_item(t, span, e.as_deref());
240 hir::ItemKind::Const(ty, body_id)
416331ca 241 }
3c0e092e 242 ItemKind::Fn(box Fn {
487cf647
FG
243 sig: FnSig { decl, header, span: fn_sig_span },
244 generics,
245 body,
3c0e092e
XL
246 ..
247 }) => {
416331ca
XL
248 self.with_new_scopes(|this| {
249 this.current_item = Some(ident.span);
250
251 // Note: we don't need to change the return type from `T` to
252 // `impl Future<Output = T>` here because lower_body
253 // only cares about the input argument patterns in the function
254 // declaration (decl), not the return types.
74b04a01 255 let asyncness = header.asyncness;
487cf647
FG
256 let body_id = this.lower_maybe_async_body(
257 span,
258 hir_id,
259 &decl,
260 asyncness,
261 body.as_deref(),
262 );
416331ca 263
f2b60f7d
FG
264 let mut itctx = ImplTraitContext::Universal;
265 let (generics, decl) = this.lower_generics(generics, id, &mut itctx, |this| {
923072b8 266 let ret_id = asyncness.opt_return_id();
487cf647 267 this.lower_fn_decl(&decl, id, *fn_sig_span, FnDeclKind::Fn, ret_id)
923072b8 268 });
3dfed10e
XL
269 let sig = hir::FnSig {
270 decl,
487cf647
FG
271 header: this.lower_fn_header(*header),
272 span: this.lower_span(*fn_sig_span),
3dfed10e 273 };
60c5eb7d 274 hir::ItemKind::Fn(sig, generics, body_id)
416331ca
XL
275 })
276 }
487cf647 277 ItemKind::Mod(_, mod_kind) => match mod_kind {
04454e1e
FG
278 ModKind::Loaded(items, _, spans) => {
279 hir::ItemKind::Mod(self.lower_mod(items, spans))
6a06907d
XL
280 }
281 ModKind::Unloaded => panic!("`mod` items should have been loaded by now"),
282 },
487cf647 283 ItemKind::ForeignMod(fm) => hir::ItemKind::ForeignMod {
94222f64
XL
284 abi: fm.abi.map_or(abi::Abi::FALLBACK, |abi| self.lower_abi(abi)),
285 items: self
286 .arena
287 .alloc_from_iter(fm.items.iter().map(|x| self.lower_foreign_item_ref(x))),
288 },
487cf647
FG
289 ItemKind::GlobalAsm(asm) => hir::ItemKind::GlobalAsm(self.lower_inline_asm(span, asm)),
290 ItemKind::TyAlias(box TyAlias { generics, where_clauses, ty: Some(ty), .. }) => {
f035d41b
XL
291 // We lower
292 //
293 // type Foo = impl Trait
294 //
295 // to
296 //
297 // type Foo = Foo1
298 // opaque type Foo1: Trait
5e7ed085 299 let mut generics = generics.clone();
487cf647 300 add_ty_alias_where_clause(&mut generics, *where_clauses, true);
923072b8 301 let (generics, ty) = self.lower_generics(
5e7ed085 302 &generics,
923072b8 303 id,
f2b60f7d
FG
304 &ImplTraitContext::Disallowed(ImplTraitPosition::Generic),
305 |this| this.lower_ty(ty, &ImplTraitContext::TypeAliasesOpaqueTy),
5099ac24 306 );
f035d41b
XL
307 hir::ItemKind::TyAlias(ty, generics)
308 }
487cf647 309 ItemKind::TyAlias(box TyAlias { generics, where_clauses, ty: None, .. }) => {
5e7ed085
FG
310 let mut generics = generics.clone();
311 add_ty_alias_where_clause(&mut generics, *where_clauses, true);
923072b8 312 let (generics, ty) = self.lower_generics(
5e7ed085 313 &generics,
923072b8 314 id,
f2b60f7d 315 &ImplTraitContext::Disallowed(ImplTraitPosition::Generic),
923072b8 316 |this| this.arena.alloc(this.ty(span, hir::TyKind::Err)),
5099ac24 317 );
74b04a01
XL
318 hir::ItemKind::TyAlias(ty, generics)
319 }
487cf647 320 ItemKind::Enum(enum_definition, generics) => {
923072b8 321 let (generics, variants) = self.lower_generics(
5099ac24 322 generics,
923072b8 323 id,
f2b60f7d 324 &ImplTraitContext::Disallowed(ImplTraitPosition::Generic),
923072b8
FG
325 |this| {
326 this.arena.alloc_from_iter(
327 enum_definition.variants.iter().map(|x| this.lower_variant(x)),
328 )
329 },
330 );
331 hir::ItemKind::Enum(hir::EnumDef { variants }, generics)
332 }
487cf647 333 ItemKind::Struct(struct_def, generics) => {
923072b8
FG
334 let (generics, struct_def) = self.lower_generics(
335 generics,
336 id,
f2b60f7d 337 &ImplTraitContext::Disallowed(ImplTraitPosition::Generic),
923072b8
FG
338 |this| this.lower_variant_data(hir_id, struct_def),
339 );
340 hir::ItemKind::Struct(struct_def, generics)
416331ca 341 }
487cf647 342 ItemKind::Union(vdata, generics) => {
923072b8
FG
343 let (generics, vdata) = self.lower_generics(
344 generics,
345 id,
f2b60f7d 346 &ImplTraitContext::Disallowed(ImplTraitPosition::Generic),
923072b8
FG
347 |this| this.lower_variant_data(hir_id, vdata),
348 );
349 hir::ItemKind::Union(vdata, generics)
416331ca 350 }
3c0e092e 351 ItemKind::Impl(box Impl {
416331ca
XL
352 unsafety,
353 polarity,
354 defaultness,
dfeec247 355 constness,
487cf647
FG
356 generics: ast_generics,
357 of_trait: trait_ref,
358 self_ty: ty,
359 items: impl_items,
5869c6ff 360 }) => {
416331ca
XL
361 // Lower the "impl header" first. This ordering is important
362 // for in-band lifetimes! Consider `'a` here:
363 //
364 // impl Foo<'a> for u32 {
365 // fn method(&'a self) { .. }
366 // }
367 //
368 // Because we start by lowering the `Foo<'a> for u32`
369 // part, we will add `'a` to the list of generics on
370 // the impl. When we then encounter it later in the
371 // method, it will not be considered an in-band
372 // lifetime to be added, but rather a reference to a
373 // parent lifetime.
f2b60f7d 374 let mut itctx = ImplTraitContext::Universal;
04454e1e 375 let (generics, (trait_ref, lowered_ty)) =
f2b60f7d 376 self.lower_generics(ast_generics, id, &mut itctx, |this| {
416331ca 377 let trait_ref = trait_ref.as_ref().map(|trait_ref| {
5099ac24
FG
378 this.lower_trait_ref(
379 trait_ref,
f2b60f7d 380 &ImplTraitContext::Disallowed(ImplTraitPosition::Trait),
5099ac24 381 )
416331ca
XL
382 });
383
5099ac24 384 let lowered_ty = this
f2b60f7d 385 .lower_ty(ty, &ImplTraitContext::Disallowed(ImplTraitPosition::Type));
416331ca
XL
386
387 (trait_ref, lowered_ty)
dfeec247 388 });
416331ca 389
04454e1e
FG
390 let new_impl_items = self
391 .arena
392 .alloc_from_iter(impl_items.iter().map(|item| self.lower_impl_item_ref(item)));
393
ba9703b0
XL
394 // `defaultness.has_value()` is never called for an `impl`, always `true` in order
395 // to not cause an assertion failure inside the `lower_defaultness` function.
396 let has_val = true;
487cf647 397 let (defaultness, defaultness_span) = self.lower_defaultness(*defaultness, has_val);
94222f64
XL
398 let polarity = match polarity {
399 ImplPolarity::Positive => ImplPolarity::Positive,
487cf647 400 ImplPolarity::Negative(s) => ImplPolarity::Negative(self.lower_span(*s)),
94222f64 401 };
04454e1e 402 hir::ItemKind::Impl(self.arena.alloc(hir::Impl {
487cf647 403 unsafety: self.lower_unsafety(*unsafety),
60c5eb7d 404 polarity,
ba9703b0
XL
405 defaultness,
406 defaultness_span,
487cf647 407 constness: self.lower_constness(*constness),
416331ca 408 generics,
dfeec247
XL
409 of_trait: trait_ref,
410 self_ty: lowered_ty,
411 items: new_impl_items,
04454e1e 412 }))
416331ca 413 }
487cf647 414 ItemKind::Trait(box Trait { is_auto, unsafety, generics, bounds, items }) => {
923072b8
FG
415 let (generics, (unsafety, items, bounds)) = self.lower_generics(
416 generics,
417 id,
f2b60f7d 418 &ImplTraitContext::Disallowed(ImplTraitPosition::Generic),
923072b8
FG
419 |this| {
420 let bounds = this.lower_param_bounds(
421 bounds,
f2b60f7d 422 &ImplTraitContext::Disallowed(ImplTraitPosition::Bound),
923072b8
FG
423 );
424 let items = this.arena.alloc_from_iter(
425 items.iter().map(|item| this.lower_trait_item_ref(item)),
426 );
487cf647 427 let unsafety = this.lower_unsafety(*unsafety);
923072b8
FG
428 (unsafety, items, bounds)
429 },
5099ac24 430 );
487cf647 431 hir::ItemKind::Trait(*is_auto, unsafety, generics, bounds, items)
416331ca 432 }
487cf647 433 ItemKind::TraitAlias(generics, bounds) => {
923072b8 434 let (generics, bounds) = self.lower_generics(
5099ac24 435 generics,
923072b8 436 id,
f2b60f7d 437 &ImplTraitContext::Disallowed(ImplTraitPosition::Generic),
923072b8
FG
438 |this| {
439 this.lower_param_bounds(
440 bounds,
f2b60f7d 441 &ImplTraitContext::Disallowed(ImplTraitPosition::Bound),
923072b8
FG
442 )
443 },
444 );
445 hir::ItemKind::TraitAlias(generics, bounds)
446 }
487cf647
FG
447 ItemKind::MacroDef(MacroDef { body, macro_rules }) => {
448 let body = P(self.lower_delim_args(body));
923072b8 449 let macro_kind = self.resolver.decl_macro_kind(self.local_def_id(id));
487cf647 450 hir::ItemKind::Macro(ast::MacroDef { body, macro_rules: *macro_rules }, macro_kind)
94222f64
XL
451 }
452 ItemKind::MacCall(..) => {
ba9703b0 453 panic!("`TyMac` should have been expanded by now")
dfeec247 454 }
416331ca 455 }
416331ca
XL
456 }
457
74b04a01
XL
458 fn lower_const_item(
459 &mut self,
460 ty: &Ty,
461 span: Span,
462 body: Option<&Expr>,
463 ) -> (&'hir hir::Ty<'hir>, hir::BodyId) {
f2b60f7d 464 let ty = self.lower_ty(ty, &ImplTraitContext::Disallowed(ImplTraitPosition::Type));
74b04a01
XL
465 (ty, self.lower_const_body(span, body))
466 }
467
923072b8 468 #[instrument(level = "debug", skip(self))]
416331ca
XL
469 fn lower_use_tree(
470 &mut self,
471 tree: &UseTree,
472 prefix: &Path,
473 id: NodeId,
04454e1e 474 vis_span: Span,
416331ca 475 ident: &mut Ident,
6a06907d 476 attrs: Option<&'hir [Attribute]>,
dfeec247 477 ) -> hir::ItemKind<'hir> {
416331ca 478 let path = &tree.prefix;
dfeec247 479 let segments = prefix.segments.iter().chain(path.segments.iter()).cloned().collect();
416331ca
XL
480
481 match tree.kind {
487cf647 482 UseTreeKind::Simple(rename) => {
416331ca
XL
483 *ident = tree.ident();
484
485 // First, apply the prefix to the path.
1b1a35ee 486 let mut path = Path { segments, span: path.span, tokens: None };
416331ca
XL
487
488 // Correctly resolve `self` imports.
489 if path.segments.len() > 1
490 && path.segments.last().unwrap().ident.name == kw::SelfLower
491 {
492 let _ = path.segments.pop();
493 if rename.is_none() {
494 *ident = path.segments.last().unwrap().ident;
495 }
496 }
497
487cf647
FG
498 let res =
499 self.expect_full_res_from_use(id).map(|res| self.lower_res(res)).collect();
500 let path = self.lower_use_path(res, &path, ParamMode::Explicit);
416331ca
XL
501 hir::ItemKind::Use(path, hir::UseKind::Single)
502 }
503 UseTreeKind::Glob => {
487cf647
FG
504 let res = self.expect_full_res(id);
505 let res = smallvec![self.lower_res(res)];
506 let path = Path { segments, span: path.span, tokens: None };
507 let path = self.lower_use_path(res, &path, ParamMode::Explicit);
416331ca
XL
508 hir::ItemKind::Use(path, hir::UseKind::Glob)
509 }
510 UseTreeKind::Nested(ref trees) => {
511 // Nested imports are desugared into simple imports.
512 // So, if we start with
513 //
514 // ```
515 // pub(x) use foo::{a, b};
516 // ```
517 //
518 // we will create three items:
519 //
520 // ```
521 // pub(x) use foo::a;
522 // pub(x) use foo::b;
523 // pub(x) use foo::{}; // <-- this is called the `ListStem`
524 // ```
525 //
526 // The first two are produced by recursively invoking
527 // `lower_use_tree` (and indeed there may be things
528 // like `use foo::{a::{b, c}}` and so forth). They
529 // wind up being directly added to
530 // `self.items`. However, the structure of this
531 // function also requires us to return one item, and
532 // for that we return the `{}` import (called the
533 // `ListStem`).
534
1b1a35ee 535 let prefix = Path { segments, span: prefix.span.to(path.span), tokens: None };
416331ca
XL
536
537 // Add all the nested `PathListItem`s to the HIR.
538 for &(ref use_tree, id) in trees {
923072b8 539 let new_hir_id = self.local_def_id(id);
416331ca
XL
540
541 let mut prefix = prefix.clone();
542
543 // Give the segments new node-ids since they are being cloned.
544 for seg in &mut prefix.segments {
2b03887a
FG
545 // Give the cloned segment the same resolution information
546 // as the old one (this is needed for stability checking).
547 let new_id = self.next_node_id();
548 self.resolver.clone_res(seg.id, new_id);
549 seg.id = new_id;
416331ca
XL
550 }
551
552 // Each `use` import is an item and thus are owners of the
553 // names in the path. Up to this point the nested import is
554 // the current owner, since we want each desugared import to
555 // own its own names, we have to adjust the owner before
556 // lowering the rest of the import.
557 self.with_hir_id_owner(id, |this| {
416331ca
XL
558 let mut ident = *ident;
559
dfeec247 560 let kind =
04454e1e 561 this.lower_use_tree(use_tree, &prefix, id, vis_span, &mut ident, attrs);
6a06907d 562 if let Some(attrs) = attrs {
3c0e092e 563 this.attrs.insert(hir::ItemLocalId::new(0), attrs);
6a06907d 564 }
dfeec247 565
c295e0f8 566 let item = hir::Item {
2b03887a 567 owner_id: hir::OwnerId { def_id: new_hir_id },
94222f64 568 ident: this.lower_ident(ident),
dfeec247 569 kind,
04454e1e 570 vis_span,
94222f64 571 span: this.lower_span(use_tree.span),
c295e0f8
XL
572 };
573 hir::OwnerNode::Item(this.arena.alloc(item))
416331ca
XL
574 });
575 }
576
487cf647
FG
577 let res =
578 self.expect_full_res_from_use(id).map(|res| self.lower_res(res)).collect();
579 let path = self.lower_use_path(res, &prefix, ParamMode::Explicit);
416331ca
XL
580 hir::ItemKind::Use(path, hir::UseKind::ListStem)
581 }
582 }
583 }
584
c295e0f8 585 fn lower_foreign_item(&mut self, i: &ForeignItem) -> &'hir hir::ForeignItem<'hir> {
6a06907d 586 let hir_id = self.lower_node_id(i.id);
2b03887a 587 let owner_id = hir_id.expect_owner();
6a06907d 588 self.lower_attrs(hir_id, &i.attrs);
c295e0f8 589 let item = hir::ForeignItem {
2b03887a 590 owner_id,
94222f64 591 ident: self.lower_ident(i.ident),
487cf647
FG
592 kind: match &i.kind {
593 ForeignItemKind::Fn(box Fn { sig, generics, .. }) => {
74b04a01 594 let fdec = &sig.decl;
f2b60f7d 595 let mut itctx = ImplTraitContext::Universal;
04454e1e 596 let (generics, (fn_dec, fn_args)) =
f2b60f7d 597 self.lower_generics(generics, i.id, &mut itctx, |this| {
416331ca 598 (
e1599b0c 599 // Disallow `impl Trait` in foreign items.
f2b60f7d
FG
600 this.lower_fn_decl(
601 fdec,
487cf647 602 i.id,
f2b60f7d
FG
603 sig.span,
604 FnDeclKind::ExternFn,
605 None,
606 ),
e1599b0c 607 this.lower_fn_params_to_names(fdec),
416331ca 608 )
04454e1e 609 });
416331ca
XL
610
611 hir::ForeignItemKind::Fn(fn_dec, fn_args, generics)
612 }
487cf647 613 ForeignItemKind::Static(t, m, _) => {
5099ac24 614 let ty =
f2b60f7d 615 self.lower_ty(t, &ImplTraitContext::Disallowed(ImplTraitPosition::Type));
487cf647 616 hir::ForeignItemKind::Static(ty, *m)
416331ca 617 }
74b04a01 618 ForeignItemKind::TyAlias(..) => hir::ForeignItemKind::Type,
ba9703b0 619 ForeignItemKind::MacCall(_) => panic!("macro shouldn't exist here"),
416331ca 620 },
04454e1e 621 vis_span: self.lower_span(i.vis.span),
94222f64 622 span: self.lower_span(i.span),
c295e0f8
XL
623 };
624 self.arena.alloc(item)
416331ca
XL
625 }
626
c295e0f8 627 fn lower_foreign_item_ref(&mut self, i: &ForeignItem) -> hir::ForeignItemRef {
fc512014 628 hir::ForeignItemRef {
2b03887a 629 id: hir::ForeignItemId { owner_id: hir::OwnerId { def_id: self.local_def_id(i.id) } },
94222f64
XL
630 ident: self.lower_ident(i.ident),
631 span: self.lower_span(i.span),
416331ca
XL
632 }
633 }
634
dfeec247 635 fn lower_variant(&mut self, v: &Variant) -> hir::Variant<'hir> {
487cf647
FG
636 let hir_id = self.lower_node_id(v.id);
637 self.lower_attrs(hir_id, &v.attrs);
e1599b0c 638 hir::Variant {
487cf647
FG
639 hir_id,
640 def_id: self.local_def_id(v.id),
641 data: self.lower_variant_data(hir_id, &v.data),
e1599b0c 642 disr_expr: v.disr_expr.as_ref().map(|e| self.lower_anon_const(e)),
94222f64
XL
643 ident: self.lower_ident(v.ident),
644 span: self.lower_span(v.span),
416331ca
XL
645 }
646 }
647
6a06907d
XL
648 fn lower_variant_data(
649 &mut self,
650 parent_id: hir::HirId,
651 vdata: &VariantData,
652 ) -> hir::VariantData<'hir> {
487cf647
FG
653 match vdata {
654 VariantData::Struct(fields, recovered) => hir::VariantData::Struct(
dfeec247 655 self.arena
6a06907d 656 .alloc_from_iter(fields.iter().enumerate().map(|f| self.lower_field_def(f))),
487cf647 657 *recovered,
416331ca 658 ),
487cf647
FG
659 VariantData::Tuple(fields, id) => {
660 let ctor_id = self.lower_node_id(*id);
6a06907d
XL
661 self.alias_attrs(ctor_id, parent_id);
662 hir::VariantData::Tuple(
663 self.arena.alloc_from_iter(
664 fields.iter().enumerate().map(|f| self.lower_field_def(f)),
665 ),
666 ctor_id,
487cf647 667 self.local_def_id(*id),
6a06907d
XL
668 )
669 }
670 VariantData::Unit(id) => {
487cf647 671 let ctor_id = self.lower_node_id(*id);
6a06907d 672 self.alias_attrs(ctor_id, parent_id);
487cf647 673 hir::VariantData::Unit(ctor_id, self.local_def_id(*id))
6a06907d 674 }
416331ca
XL
675 }
676 }
677
94222f64 678 fn lower_field_def(&mut self, (index, f): (usize, &FieldDef)) -> hir::FieldDef<'hir> {
487cf647 679 let ty = if let TyKind::Path(qself, path) = &f.ty.kind {
416331ca
XL
680 let t = self.lower_path_ty(
681 &f.ty,
682 qself,
683 path,
684 ParamMode::ExplicitNamed, // no `'_` in declarations (Issue #61124)
f2b60f7d 685 &ImplTraitContext::Disallowed(ImplTraitPosition::Path),
416331ca 686 );
dfeec247 687 self.arena.alloc(t)
416331ca 688 } else {
f2b60f7d 689 self.lower_ty(&f.ty, &ImplTraitContext::Disallowed(ImplTraitPosition::Type))
416331ca 690 };
6a06907d
XL
691 let hir_id = self.lower_node_id(f.id);
692 self.lower_attrs(hir_id, &f.attrs);
693 hir::FieldDef {
94222f64 694 span: self.lower_span(f.span),
6a06907d 695 hir_id,
487cf647 696 def_id: self.local_def_id(f.id),
416331ca 697 ident: match f.ident {
94222f64 698 Some(ident) => self.lower_ident(ident),
416331ca 699 // FIXME(jseyfried): positional field hygiene.
94222f64 700 None => Ident::new(sym::integer(index), self.lower_span(f.span)),
416331ca 701 },
04454e1e 702 vis_span: self.lower_span(f.vis.span),
416331ca 703 ty,
416331ca
XL
704 }
705 }
706
c295e0f8 707 fn lower_trait_item(&mut self, i: &AssocItem) -> &'hir hir::TraitItem<'hir> {
6a06907d 708 let hir_id = self.lower_node_id(i.id);
487cf647 709 self.lower_attrs(hir_id, &i.attrs);
6a06907d 710 let trait_item_def_id = hir_id.expect_owner();
416331ca 711
487cf647
FG
712 let (generics, kind, has_default) = match &i.kind {
713 AssocItemKind::Const(_, ty, default) => {
f2b60f7d 714 let ty = self.lower_ty(ty, &ImplTraitContext::Disallowed(ImplTraitPosition::Type));
74b04a01 715 let body = default.as_ref().map(|x| self.lower_const_body(i.span, Some(x)));
064997fb 716 (hir::Generics::empty(), hir::TraitItemKind::Const(ty, body), body.is_some())
dfeec247 717 }
487cf647 718 AssocItemKind::Fn(box Fn { sig, generics, body: None, .. }) => {
f2b60f7d 719 let asyncness = sig.header.asyncness;
e1599b0c 720 let names = self.lower_fn_params_to_names(&sig.decl);
f2b60f7d
FG
721 let (generics, sig) = self.lower_method_sig(
722 generics,
723 sig,
724 i.id,
725 FnDeclKind::Trait,
726 asyncness.opt_return_id(),
727 );
064997fb 728 (generics, hir::TraitItemKind::Fn(sig, hir::TraitFn::Required(names)), false)
416331ca 729 }
487cf647 730 AssocItemKind::Fn(box Fn { sig, generics, body: Some(body), .. }) => {
cdc7bbd5
XL
731 let asyncness = sig.header.asyncness;
732 let body_id =
487cf647 733 self.lower_maybe_async_body(i.span, hir_id, &sig.decl, asyncness, Some(&body));
cdc7bbd5
XL
734 let (generics, sig) = self.lower_method_sig(
735 generics,
736 sig,
04454e1e 737 i.id,
5099ac24 738 FnDeclKind::Trait,
cdc7bbd5 739 asyncness.opt_return_id(),
cdc7bbd5 740 );
064997fb 741 (generics, hir::TraitItemKind::Fn(sig, hir::TraitFn::Provided(body_id)), true)
416331ca 742 }
487cf647 743 AssocItemKind::Type(box TyAlias { generics, where_clauses, bounds, ty, .. }) => {
5e7ed085 744 let mut generics = generics.clone();
487cf647 745 add_ty_alias_where_clause(&mut generics, *where_clauses, false);
064997fb 746 let (generics, kind) = self.lower_generics(
5e7ed085 747 &generics,
923072b8 748 i.id,
f2b60f7d 749 &ImplTraitContext::Disallowed(ImplTraitPosition::Generic),
923072b8
FG
750 |this| {
751 let ty = ty.as_ref().map(|x| {
f2b60f7d 752 this.lower_ty(x, &ImplTraitContext::Disallowed(ImplTraitPosition::Type))
923072b8
FG
753 });
754 hir::TraitItemKind::Type(
755 this.lower_param_bounds(
756 bounds,
f2b60f7d 757 &ImplTraitContext::Disallowed(ImplTraitPosition::Generic),
923072b8
FG
758 ),
759 ty,
760 )
761 },
064997fb
FG
762 );
763 (generics, kind, ty.is_some())
dfeec247 764 }
ba9703b0 765 AssocItemKind::MacCall(..) => panic!("macro item shouldn't exist at this point"),
416331ca
XL
766 };
767
c295e0f8 768 let item = hir::TraitItem {
2b03887a 769 owner_id: trait_item_def_id,
94222f64
XL
770 ident: self.lower_ident(i.ident),
771 generics,
772 kind,
773 span: self.lower_span(i.span),
064997fb 774 defaultness: hir::Defaultness::Default { has_value: has_default },
c295e0f8
XL
775 };
776 self.arena.alloc(item)
416331ca
XL
777 }
778
dfeec247 779 fn lower_trait_item_ref(&mut self, i: &AssocItem) -> hir::TraitItemRef {
064997fb
FG
780 let kind = match &i.kind {
781 AssocItemKind::Const(..) => hir::AssocItemKind::Const,
2b03887a 782 AssocItemKind::Type(..) => hir::AssocItemKind::Type,
064997fb
FG
783 AssocItemKind::Fn(box Fn { sig, .. }) => {
784 hir::AssocItemKind::Fn { has_self: sig.decl.has_self() }
416331ca 785 }
ba9703b0 786 AssocItemKind::MacCall(..) => unimplemented!(),
416331ca 787 };
2b03887a 788 let id = hir::TraitItemId { owner_id: hir::OwnerId { def_id: self.local_def_id(i.id) } };
94222f64
XL
789 hir::TraitItemRef {
790 id,
791 ident: self.lower_ident(i.ident),
792 span: self.lower_span(i.span),
94222f64
XL
793 kind,
794 }
416331ca
XL
795 }
796
dfeec247 797 /// Construct `ExprKind::Err` for the given `span`.
923072b8 798 pub(crate) fn expr_err(&mut self, span: Span) -> hir::Expr<'hir> {
487cf647 799 self.expr(span, hir::ExprKind::Err)
dfeec247
XL
800 }
801
c295e0f8 802 fn lower_impl_item(&mut self, i: &AssocItem) -> &'hir hir::ImplItem<'hir> {
064997fb
FG
803 // Since `default impl` is not yet implemented, this is always true in impls.
804 let has_value = true;
805 let (defaultness, _) = self.lower_defaultness(i.kind.defaultness(), has_value);
487cf647
FG
806 let hir_id = self.lower_node_id(i.id);
807 self.lower_attrs(hir_id, &i.attrs);
064997fb 808
74b04a01
XL
809 let (generics, kind) = match &i.kind {
810 AssocItemKind::Const(_, ty, expr) => {
f2b60f7d 811 let ty = self.lower_ty(ty, &ImplTraitContext::Disallowed(ImplTraitPosition::Type));
dfeec247 812 (
74b04a01 813 hir::Generics::empty(),
dfeec247
XL
814 hir::ImplItemKind::Const(ty, self.lower_const_body(i.span, expr.as_deref())),
815 )
816 }
3c0e092e 817 AssocItemKind::Fn(box Fn { sig, generics, body, .. }) => {
416331ca 818 self.current_item = Some(i.span);
74b04a01 819 let asyncness = sig.header.asyncness;
487cf647
FG
820 let body_id = self.lower_maybe_async_body(
821 i.span,
822 hir_id,
823 &sig.decl,
824 asyncness,
825 body.as_deref(),
826 );
416331ca 827 let (generics, sig) = self.lower_method_sig(
74b04a01 828 generics,
416331ca 829 sig,
04454e1e 830 i.id,
5099ac24 831 if self.is_in_trait_impl { FnDeclKind::Impl } else { FnDeclKind::Inherent },
74b04a01 832 asyncness.opt_return_id(),
416331ca
XL
833 );
834
ba9703b0 835 (generics, hir::ImplItemKind::Fn(sig, body_id))
416331ca 836 }
2b03887a 837 AssocItemKind::Type(box TyAlias { generics, where_clauses, ty, .. }) => {
5e7ed085
FG
838 let mut generics = generics.clone();
839 add_ty_alias_where_clause(&mut generics, *where_clauses, false);
923072b8 840 self.lower_generics(
5e7ed085 841 &generics,
923072b8 842 i.id,
f2b60f7d 843 &ImplTraitContext::Disallowed(ImplTraitPosition::Generic),
923072b8
FG
844 |this| match ty {
845 None => {
846 let ty = this.arena.alloc(this.ty(i.span, hir::TyKind::Err));
2b03887a 847 hir::ImplItemKind::Type(ty)
923072b8
FG
848 }
849 Some(ty) => {
f2b60f7d 850 let ty = this.lower_ty(ty, &ImplTraitContext::TypeAliasesOpaqueTy);
2b03887a 851 hir::ImplItemKind::Type(ty)
923072b8
FG
852 }
853 },
854 )
dfeec247 855 }
ba9703b0 856 AssocItemKind::MacCall(..) => panic!("`TyMac` should have been expanded by now"),
416331ca
XL
857 };
858
c295e0f8 859 let item = hir::ImplItem {
2b03887a 860 owner_id: hir_id.expect_owner(),
94222f64 861 ident: self.lower_ident(i.ident),
416331ca 862 generics,
e74abb32 863 kind,
04454e1e 864 vis_span: self.lower_span(i.vis.span),
94222f64 865 span: self.lower_span(i.span),
064997fb 866 defaultness,
c295e0f8
XL
867 };
868 self.arena.alloc(item)
416331ca
XL
869 }
870
c295e0f8 871 fn lower_impl_item_ref(&mut self, i: &AssocItem) -> hir::ImplItemRef {
416331ca 872 hir::ImplItemRef {
2b03887a 873 id: hir::ImplItemId { owner_id: hir::OwnerId { def_id: self.local_def_id(i.id) } },
94222f64
XL
874 ident: self.lower_ident(i.ident),
875 span: self.lower_span(i.span),
60c5eb7d 876 kind: match &i.kind {
dfeec247 877 AssocItemKind::Const(..) => hir::AssocItemKind::Const,
2b03887a 878 AssocItemKind::Type(..) => hir::AssocItemKind::Type,
3c0e092e 879 AssocItemKind::Fn(box Fn { sig, .. }) => {
ba9703b0 880 hir::AssocItemKind::Fn { has_self: sig.decl.has_self() }
dfeec247 881 }
ba9703b0 882 AssocItemKind::MacCall(..) => unimplemented!(),
416331ca 883 },
2b03887a
FG
884 trait_item_def_id: self
885 .resolver
886 .get_partial_res(i.id)
887 .map(|r| r.expect_full_res().def_id()),
416331ca 888 }
416331ca
XL
889 }
890
ba9703b0
XL
891 fn lower_defaultness(
892 &self,
893 d: Defaultness,
894 has_value: bool,
895 ) -> (hir::Defaultness, Option<Span>) {
416331ca 896 match d {
94222f64
XL
897 Defaultness::Default(sp) => {
898 (hir::Defaultness::Default { has_value }, Some(self.lower_span(sp)))
899 }
416331ca
XL
900 Defaultness::Final => {
901 assert!(has_value);
ba9703b0 902 (hir::Defaultness::Final, None)
416331ca
XL
903 }
904 }
905 }
906
dfeec247
XL
907 fn record_body(
908 &mut self,
909 params: &'hir [hir::Param<'hir>],
910 value: hir::Expr<'hir>,
911 ) -> hir::BodyId {
f2b60f7d
FG
912 let body = hir::Body {
913 generator_kind: self.generator_kind,
914 params,
915 value: self.arena.alloc(value),
916 };
416331ca 917 let id = body.id();
3c0e092e
XL
918 debug_assert_eq!(id.hir_id.owner, self.current_hir_id_owner);
919 self.bodies.push((id.hir_id.local_id, self.arena.alloc(body)));
416331ca
XL
920 id
921 }
922
ba9703b0 923 pub(super) fn lower_body(
416331ca 924 &mut self,
dfeec247 925 f: impl FnOnce(&mut Self) -> (&'hir [hir::Param<'hir>], hir::Expr<'hir>),
416331ca
XL
926 ) -> hir::BodyId {
927 let prev_gen_kind = self.generator_kind.take();
ba9703b0 928 let task_context = self.task_context.take();
e1599b0c
XL
929 let (parameters, result) = f(self);
930 let body_id = self.record_body(parameters, result);
ba9703b0 931 self.task_context = task_context;
416331ca
XL
932 self.generator_kind = prev_gen_kind;
933 body_id
934 }
935
dfeec247 936 fn lower_param(&mut self, param: &Param) -> hir::Param<'hir> {
6a06907d
XL
937 let hir_id = self.lower_node_id(param.id);
938 self.lower_attrs(hir_id, &param.attrs);
e1599b0c 939 hir::Param {
6a06907d 940 hir_id,
e1599b0c 941 pat: self.lower_pat(&param.pat),
94222f64
XL
942 ty_span: self.lower_span(param.ty.span),
943 span: self.lower_span(param.span),
416331ca
XL
944 }
945 }
946
947 pub(super) fn lower_fn_body(
948 &mut self,
949 decl: &FnDecl,
dfeec247 950 body: impl FnOnce(&mut Self) -> hir::Expr<'hir>,
416331ca 951 ) -> hir::BodyId {
dfeec247
XL
952 self.lower_body(|this| {
953 (
954 this.arena.alloc_from_iter(decl.inputs.iter().map(|x| this.lower_param(x))),
955 body(this),
956 )
957 })
416331ca
XL
958 }
959
dfeec247
XL
960 fn lower_fn_body_block(
961 &mut self,
962 span: Span,
963 decl: &FnDecl,
964 body: Option<&Block>,
965 ) -> hir::BodyId {
966 self.lower_fn_body(decl, |this| this.lower_block_expr_opt(span, body))
416331ca
XL
967 }
968
dfeec247
XL
969 fn lower_block_expr_opt(&mut self, span: Span, block: Option<&Block>) -> hir::Expr<'hir> {
970 match block {
971 Some(block) => self.lower_block_expr(block),
972 None => self.expr_err(span),
973 }
974 }
975
976 pub(super) fn lower_const_body(&mut self, span: Span, expr: Option<&Expr>) -> hir::BodyId {
977 self.lower_body(|this| {
978 (
979 &[],
980 match expr {
981 Some(expr) => this.lower_expr_mut(expr),
982 None => this.expr_err(span),
983 },
984 )
985 })
416331ca
XL
986 }
987
988 fn lower_maybe_async_body(
989 &mut self,
dfeec247 990 span: Span,
487cf647 991 fn_id: hir::HirId,
416331ca 992 decl: &FnDecl,
74b04a01 993 asyncness: Async,
dfeec247 994 body: Option<&Block>,
416331ca 995 ) -> hir::BodyId {
2b03887a
FG
996 let (closure_id, body) = match (asyncness, body) {
997 (Async::Yes { closure_id, .. }, Some(body)) => (closure_id, body),
998 _ => return self.lower_fn_body_block(span, decl, body),
416331ca
XL
999 };
1000
1001 self.lower_body(|this| {
dfeec247
XL
1002 let mut parameters: Vec<hir::Param<'_>> = Vec::new();
1003 let mut statements: Vec<hir::Stmt<'_>> = Vec::new();
416331ca 1004
e1599b0c 1005 // Async function parameters are lowered into the closure body so that they are
416331ca
XL
1006 // captured and so that the drop order matches the equivalent non-async functions.
1007 //
1008 // from:
1009 //
1010 // async fn foo(<pattern>: <ty>, <pattern>: <ty>, <pattern>: <ty>) {
e1599b0c 1011 // <body>
416331ca
XL
1012 // }
1013 //
1014 // into:
1015 //
1016 // fn foo(__arg0: <ty>, __arg1: <ty>, __arg2: <ty>) {
1017 // async move {
1018 // let __arg2 = __arg2;
1019 // let <pattern> = __arg2;
1020 // let __arg1 = __arg1;
1021 // let <pattern> = __arg1;
1022 // let __arg0 = __arg0;
1023 // let <pattern> = __arg0;
e1599b0c 1024 // drop-temps { <body> } // see comments later in fn for details
416331ca
XL
1025 // }
1026 // }
1027 //
1028 // If `<pattern>` is a simple ident, then it is lowered to a single
1029 // `let <pattern> = <pattern>;` statement as an optimization.
e1599b0c
XL
1030 //
1031 // Note that the body is embedded in `drop-temps`; an
1032 // equivalent desugaring would be `return { <body>
1033 // };`. The key point is that we wish to drop all the
1034 // let-bound variables and temporaries created in the body
1035 // (and its tail expression!) before we drop the
1036 // parameters (c.f. rust-lang/rust#64512).
1037 for (index, parameter) in decl.inputs.iter().enumerate() {
1038 let parameter = this.lower_param(parameter);
1039 let span = parameter.pat.span;
416331ca
XL
1040
1041 // Check if this is a binding pattern, if so, we can optimize and avoid adding a
e1599b0c 1042 // `let <pat> = __argN;` statement. In this case, we do not rename the parameter.
e74abb32 1043 let (ident, is_simple_parameter) = match parameter.pat.kind {
f2b60f7d
FG
1044 hir::PatKind::Binding(hir::BindingAnnotation(ByRef::No, _), _, ident, _) => {
1045 (ident, true)
1046 }
29967ef6
XL
1047 // For `ref mut` or wildcard arguments, we can't reuse the binding, but
1048 // we can keep the same name for the parameter.
1049 // This lets rustdoc render it correctly in documentation.
1050 hir::PatKind::Binding(_, _, ident, _) => (ident, false),
1051 hir::PatKind::Wild => {
1052 (Ident::with_dummy_span(rustc_span::symbol::kw::Underscore), false)
dfeec247 1053 }
416331ca
XL
1054 _ => {
1055 // Replace the ident for bindings that aren't simple.
1056 let name = format!("__arg{}", index);
1057 let ident = Ident::from_str(&name);
1058
1059 (ident, false)
dfeec247 1060 }
416331ca
XL
1061 };
1062
dfeec247 1063 let desugared_span = this.mark_span_with_reason(DesugaringKind::Async, span, None);
416331ca 1064
e1599b0c 1065 // Construct a parameter representing `__argN: <ty>` to replace the parameter of the
416331ca
XL
1066 // async function.
1067 //
e1599b0c
XL
1068 // If this is the simple case, this parameter will end up being the same as the
1069 // original parameter, but with a different pattern id.
3c0e092e 1070 let stmt_attrs = this.attrs.get(&parameter.hir_id.local_id).copied();
e1599b0c
XL
1071 let (new_parameter_pat, new_parameter_id) = this.pat_ident(desugared_span, ident);
1072 let new_parameter = hir::Param {
e1599b0c
XL
1073 hir_id: parameter.hir_id,
1074 pat: new_parameter_pat,
94222f64
XL
1075 ty_span: this.lower_span(parameter.ty_span),
1076 span: this.lower_span(parameter.span),
416331ca
XL
1077 };
1078
e1599b0c 1079 if is_simple_parameter {
416331ca
XL
1080 // If this is the simple case, then we only insert one statement that is
1081 // `let <pat> = <pat>;`. We re-use the original argument's pattern so that
1082 // `HirId`s are densely assigned.
e1599b0c 1083 let expr = this.expr_ident(desugared_span, ident, new_parameter_id);
416331ca
XL
1084 let stmt = this.stmt_let_pat(
1085 stmt_attrs,
1086 desugared_span,
dfeec247 1087 Some(expr),
e1599b0c 1088 parameter.pat,
dfeec247 1089 hir::LocalSource::AsyncFn,
416331ca
XL
1090 );
1091 statements.push(stmt);
1092 } else {
1093 // If this is not the simple case, then we construct two statements:
1094 //
1095 // ```
1096 // let __argN = __argN;
1097 // let <pat> = __argN;
1098 // ```
1099 //
e1599b0c 1100 // The first statement moves the parameter into the closure and thus ensures
416331ca
XL
1101 // that the drop order is correct.
1102 //
1103 // The second statement creates the bindings that the user wrote.
1104
1105 // Construct the `let mut __argN = __argN;` statement. It must be a mut binding
1106 // because the user may have specified a `ref mut` binding in the next
1107 // statement.
1108 let (move_pat, move_id) = this.pat_ident_binding_mode(
dfeec247
XL
1109 desugared_span,
1110 ident,
f2b60f7d 1111 hir::BindingAnnotation::MUT,
dfeec247 1112 );
e1599b0c 1113 let move_expr = this.expr_ident(desugared_span, ident, new_parameter_id);
416331ca 1114 let move_stmt = this.stmt_let_pat(
6a06907d 1115 None,
416331ca 1116 desugared_span,
dfeec247 1117 Some(move_expr),
416331ca 1118 move_pat,
dfeec247 1119 hir::LocalSource::AsyncFn,
416331ca
XL
1120 );
1121
1122 // Construct the `let <pat> = __argN;` statement. We re-use the original
e1599b0c 1123 // parameter's pattern so that `HirId`s are densely assigned.
416331ca
XL
1124 let pattern_expr = this.expr_ident(desugared_span, ident, move_id);
1125 let pattern_stmt = this.stmt_let_pat(
1126 stmt_attrs,
1127 desugared_span,
dfeec247 1128 Some(pattern_expr),
e1599b0c 1129 parameter.pat,
dfeec247 1130 hir::LocalSource::AsyncFn,
416331ca
XL
1131 );
1132
1133 statements.push(move_stmt);
1134 statements.push(pattern_stmt);
1135 };
1136
e1599b0c 1137 parameters.push(new_parameter);
416331ca
XL
1138 }
1139
1140 let async_expr = this.make_async_expr(
e74abb32 1141 CaptureBy::Value,
487cf647 1142 Some(fn_id),
e74abb32
XL
1143 closure_id,
1144 None,
2b03887a 1145 body.span,
e74abb32 1146 hir::AsyncGeneratorKind::Fn,
416331ca 1147 |this| {
e1599b0c 1148 // Create a block from the user's function body:
2b03887a 1149 let user_body = this.lower_block_expr(body);
e1599b0c
XL
1150
1151 // Transform into `drop-temps { <user-body> }`, an expression:
dfeec247
XL
1152 let desugared_span =
1153 this.mark_span_with_reason(DesugaringKind::Async, user_body.span, None);
487cf647
FG
1154 let user_body =
1155 this.expr_drop_temps(desugared_span, this.arena.alloc(user_body));
e1599b0c
XL
1156
1157 // As noted above, create the final block like
1158 //
1159 // ```
1160 // {
1161 // let $param_pattern = $raw_param;
1162 // ...
1163 // drop-temps { <user-body> }
1164 // }
1165 // ```
1166 let body = this.block_all(
1167 desugared_span,
dfeec247
XL
1168 this.arena.alloc_from_iter(statements),
1169 Some(user_body),
e1599b0c 1170 );
dfeec247 1171
487cf647 1172 this.expr_block(body)
dfeec247
XL
1173 },
1174 );
1175
487cf647 1176 (this.arena.alloc_from_iter(parameters), this.expr(body.span, async_expr))
416331ca
XL
1177 })
1178 }
1179
1180 fn lower_method_sig(
1181 &mut self,
1182 generics: &Generics,
60c5eb7d 1183 sig: &FnSig,
04454e1e 1184 id: NodeId,
5099ac24 1185 kind: FnDeclKind,
f2b60f7d 1186 is_async: Option<(NodeId, Span)>,
04454e1e 1187 ) -> (&'hir hir::Generics<'hir>, hir::FnSig<'hir>) {
94222f64 1188 let header = self.lower_fn_header(sig.header);
f2b60f7d
FG
1189 let mut itctx = ImplTraitContext::Universal;
1190 let (generics, decl) = self.lower_generics(generics, id, &mut itctx, |this| {
487cf647 1191 this.lower_fn_decl(&sig.decl, id, sig.span, kind, is_async)
04454e1e 1192 });
94222f64 1193 (generics, hir::FnSig { header, decl, span: self.lower_span(sig.span) })
416331ca
XL
1194 }
1195
94222f64 1196 fn lower_fn_header(&mut self, h: FnHeader) -> hir::FnHeader {
416331ca 1197 hir::FnHeader {
74b04a01
XL
1198 unsafety: self.lower_unsafety(h.unsafety),
1199 asyncness: self.lower_asyncness(h.asyncness),
1200 constness: self.lower_constness(h.constness),
94222f64 1201 abi: self.lower_extern(h.ext),
416331ca
XL
1202 }
1203 }
1204
60c5eb7d 1205 pub(super) fn lower_abi(&mut self, abi: StrLit) -> abi::Abi {
a2a8927a 1206 abi::lookup(abi.symbol_unescaped.as_str()).unwrap_or_else(|| {
60c5eb7d
XL
1207 self.error_on_invalid_abi(abi);
1208 abi::Abi::Rust
1209 })
416331ca
XL
1210 }
1211
94222f64 1212 pub(super) fn lower_extern(&mut self, ext: Extern) -> abi::Abi {
60c5eb7d
XL
1213 match ext {
1214 Extern::None => abi::Abi::Rust,
064997fb
FG
1215 Extern::Implicit(_) => abi::Abi::FALLBACK,
1216 Extern::Explicit(abi, _) => self.lower_abi(abi),
416331ca
XL
1217 }
1218 }
1219
60c5eb7d 1220 fn error_on_invalid_abi(&self, abi: StrLit) {
2b03887a
FG
1221 let abi_names = abi::enabled_names(self.tcx.features(), abi.span)
1222 .iter()
1223 .map(|s| Symbol::intern(s))
1224 .collect::<Vec<_>>();
1225 let suggested_name = find_best_match_for_name(&abi_names, abi.symbol_unescaped, None);
f2b60f7d 1226 self.tcx.sess.emit_err(InvalidAbi {
2b03887a 1227 abi: abi.symbol_unescaped,
f2b60f7d 1228 span: abi.span,
2b03887a
FG
1229 suggestion: suggested_name.map(|suggested_name| InvalidAbiSuggestion {
1230 span: abi.span,
1231 suggestion: format!("\"{suggested_name}\""),
1232 }),
1233 command: "rustc --print=calling-conventions".to_string(),
f2b60f7d 1234 });
60c5eb7d
XL
1235 }
1236
74b04a01 1237 fn lower_asyncness(&mut self, a: Async) -> hir::IsAsync {
416331ca 1238 match a {
74b04a01
XL
1239 Async::Yes { .. } => hir::IsAsync::Async,
1240 Async::No => hir::IsAsync::NotAsync,
1241 }
1242 }
1243
1244 fn lower_constness(&mut self, c: Const) -> hir::Constness {
1245 match c {
1246 Const::Yes(_) => hir::Constness::Const,
1247 Const::No => hir::Constness::NotConst,
1248 }
1249 }
1250
1251 pub(super) fn lower_unsafety(&mut self, u: Unsafe) -> hir::Unsafety {
1252 match u {
1253 Unsafe::Yes(_) => hir::Unsafety::Unsafe,
1254 Unsafe::No => hir::Unsafety::Normal,
416331ca
XL
1255 }
1256 }
1257
923072b8
FG
1258 /// Return the pair of the lowered `generics` as `hir::Generics` and the evaluation of `f` with
1259 /// the carried impl trait definitions and bounds.
1260 #[instrument(level = "debug", skip(self, f))]
1261 fn lower_generics<T>(
416331ca
XL
1262 &mut self,
1263 generics: &Generics,
923072b8 1264 parent_node_id: NodeId,
f2b60f7d 1265 itctx: &ImplTraitContext,
923072b8
FG
1266 f: impl FnOnce(&mut Self) -> T,
1267 ) -> (&'hir hir::Generics<'hir>, T) {
1268 debug_assert!(self.impl_trait_defs.is_empty());
1269 debug_assert!(self.impl_trait_bounds.is_empty());
1270
5e7ed085 1271 // Error if `?Trait` bounds in where clauses don't refer directly to type parameters.
c295e0f8
XL
1272 // Note: we used to clone these bounds directly onto the type parameter (and avoid lowering
1273 // these into hir when we lower thee where clauses), but this makes it quite difficult to
1274 // keep track of the Span info. Now, `add_implicitly_sized` in `AstConv` checks both param bounds and
1275 // where clauses for `?Sized`.
416331ca 1276 for pred in &generics.where_clause.predicates {
487cf647 1277 let WherePredicate::BoundPredicate(bound_pred) = pred else {
5e7ed085 1278 continue;
c295e0f8
XL
1279 };
1280 let compute_is_param = || {
1281 // Check if the where clause type is a plain type parameter.
1282 match self
1283 .resolver
1284 .get_partial_res(bound_pred.bounded_ty.id)
2b03887a 1285 .and_then(|r| r.full_res())
c295e0f8 1286 {
2b03887a 1287 Some(Res::Def(DefKind::TyParam, def_id))
c295e0f8
XL
1288 if bound_pred.bound_generic_params.is_empty() =>
1289 {
1290 generics
1291 .params
1292 .iter()
923072b8 1293 .any(|p| def_id == self.local_def_id(p.id).to_def_id())
416331ca 1294 }
c295e0f8
XL
1295 // Either the `bounded_ty` is not a plain type parameter, or
1296 // it's not found in the generic type parameters list.
1297 _ => false,
1298 }
1299 };
1300 // We only need to compute this once per `WherePredicate`, but don't
1301 // need to compute this at all unless there is a Maybe bound.
1302 let mut is_param: Option<bool> = None;
1303 for bound in &bound_pred.bounds {
1304 if !matches!(*bound, GenericBound::Trait(_, TraitBoundModifier::Maybe)) {
1305 continue;
1306 }
1307 let is_param = *is_param.get_or_insert_with(compute_is_param);
1308 if !is_param {
f2b60f7d 1309 self.tcx.sess.emit_err(MisplacedRelaxTraitBound { span: bound.span() });
416331ca
XL
1310 }
1311 }
1312 }
1313
923072b8 1314 let mut predicates: SmallVec<[hir::WherePredicate<'hir>; 4]> = SmallVec::new();
04454e1e 1315 predicates.extend(generics.params.iter().filter_map(|param| {
04454e1e
FG
1316 self.lower_generic_bound_predicate(
1317 param.ident,
1318 param.id,
1319 &param.kind,
064997fb
FG
1320 &param.bounds,
1321 itctx,
04454e1e
FG
1322 PredicateOrigin::GenericParam,
1323 )
1324 }));
1325 predicates.extend(
1326 generics
1327 .where_clause
1328 .predicates
1329 .iter()
1330 .map(|predicate| self.lower_where_predicate(predicate)),
1331 );
1332
923072b8
FG
1333 let mut params: SmallVec<[hir::GenericParam<'hir>; 4]> =
1334 self.lower_generic_params_mut(&generics.params).collect();
416331ca 1335
923072b8
FG
1336 // Introduce extra lifetimes if late resolution tells us to.
1337 let extra_lifetimes = self.resolver.take_extra_lifetime_params(parent_node_id);
1338 params.extend(extra_lifetimes.into_iter().filter_map(|(ident, node_id, res)| {
1339 self.lifetime_res_to_generic_param(ident, node_id, res)
1340 }));
1341
1342 let has_where_clause_predicates = !generics.where_clause.predicates.is_empty();
1343 let where_clause_span = self.lower_span(generics.where_clause.span);
1344 let span = self.lower_span(generics.span);
1345 let res = f(self);
1346
1347 let impl_trait_defs = std::mem::take(&mut self.impl_trait_defs);
1348 params.extend(impl_trait_defs.into_iter());
1349
1350 let impl_trait_bounds = std::mem::take(&mut self.impl_trait_bounds);
1351 predicates.extend(impl_trait_bounds.into_iter());
1352
1353 let lowered_generics = self.arena.alloc(hir::Generics {
1354 params: self.arena.alloc_from_iter(params),
1355 predicates: self.arena.alloc_from_iter(predicates),
1356 has_where_clause_predicates,
1357 where_clause_span,
1358 span,
1359 });
1360
1361 (lowered_generics, res)
dfeec247
XL
1362 }
1363
04454e1e
FG
1364 pub(super) fn lower_generic_bound_predicate(
1365 &mut self,
1366 ident: Ident,
1367 id: NodeId,
1368 kind: &GenericParamKind,
064997fb 1369 bounds: &[GenericBound],
f2b60f7d 1370 itctx: &ImplTraitContext,
04454e1e
FG
1371 origin: PredicateOrigin,
1372 ) -> Option<hir::WherePredicate<'hir>> {
1373 // Do not create a clause if we do not have anything inside it.
1374 if bounds.is_empty() {
1375 return None;
1376 }
064997fb
FG
1377
1378 let bounds = self.lower_param_bounds(bounds, itctx);
1379
04454e1e
FG
1380 let ident = self.lower_ident(ident);
1381 let param_span = ident.span;
1382 let span = bounds
1383 .iter()
1384 .fold(Some(param_span.shrink_to_hi()), |span: Option<Span>, bound| {
1385 let bound_span = bound.span();
1386 // We include bounds that come from a `#[derive(_)]` but point at the user's code,
1387 // as we use this method to get a span appropriate for suggestions.
1388 if !bound_span.can_be_used_for_suggestions() {
1389 None
1390 } else if let Some(span) = span {
1391 Some(span.to(bound_span))
1392 } else {
1393 Some(bound_span)
1394 }
1395 })
1396 .unwrap_or(param_span.shrink_to_hi());
1397 match kind {
1398 GenericParamKind::Const { .. } => None,
1399 GenericParamKind::Type { .. } => {
923072b8 1400 let def_id = self.local_def_id(id).to_def_id();
f2b60f7d
FG
1401 let hir_id = self.next_id();
1402 let res = Res::Def(DefKind::TyParam, def_id);
04454e1e
FG
1403 let ty_path = self.arena.alloc(hir::Path {
1404 span: param_span,
f2b60f7d
FG
1405 res,
1406 segments: self
1407 .arena
1408 .alloc_from_iter([hir::PathSegment::new(ident, hir_id, res)]),
04454e1e
FG
1409 });
1410 let ty_id = self.next_id();
1411 let bounded_ty =
1412 self.ty_path(ty_id, param_span, hir::QPath::Resolved(None, ty_path));
1413 Some(hir::WherePredicate::BoundPredicate(hir::WhereBoundPredicate {
2b03887a 1414 hir_id: self.next_id(),
04454e1e
FG
1415 bounded_ty: self.arena.alloc(bounded_ty),
1416 bounds,
1417 span,
1418 bound_generic_params: &[],
1419 origin,
1420 }))
dfeec247 1421 }
04454e1e 1422 GenericParamKind::Lifetime => {
04454e1e 1423 let ident = self.lower_ident(ident);
923072b8 1424 let lt_id = self.next_node_id();
487cf647 1425 let lifetime = self.new_named_lifetime(id, lt_id, ident);
04454e1e
FG
1426 Some(hir::WherePredicate::RegionPredicate(hir::WhereRegionPredicate {
1427 lifetime,
1428 span,
1429 bounds,
1430 in_where_clause: false,
1431 }))
1432 }
1433 }
416331ca
XL
1434 }
1435
dfeec247 1436 fn lower_where_predicate(&mut self, pred: &WherePredicate) -> hir::WherePredicate<'hir> {
487cf647 1437 match pred {
416331ca 1438 WherePredicate::BoundPredicate(WhereBoundPredicate {
487cf647
FG
1439 bound_generic_params,
1440 bounded_ty,
1441 bounds,
416331ca 1442 span,
04454e1e 1443 }) => hir::WherePredicate::BoundPredicate(hir::WhereBoundPredicate {
2b03887a 1444 hir_id: self.next_id(),
04454e1e
FG
1445 bound_generic_params: self.lower_generic_params(bound_generic_params),
1446 bounded_ty: self
f2b60f7d 1447 .lower_ty(bounded_ty, &ImplTraitContext::Disallowed(ImplTraitPosition::Type)),
04454e1e
FG
1448 bounds: self.arena.alloc_from_iter(bounds.iter().map(|bound| {
1449 self.lower_param_bound(
1450 bound,
f2b60f7d 1451 &ImplTraitContext::Disallowed(ImplTraitPosition::Bound),
04454e1e
FG
1452 )
1453 })),
487cf647 1454 span: self.lower_span(*span),
04454e1e 1455 origin: PredicateOrigin::WhereClause,
c295e0f8 1456 }),
487cf647
FG
1457 WherePredicate::RegionPredicate(WhereRegionPredicate { lifetime, bounds, span }) => {
1458 hir::WherePredicate::RegionPredicate(hir::WhereRegionPredicate {
1459 span: self.lower_span(*span),
1460 lifetime: self.lower_lifetime(lifetime),
1461 bounds: self.lower_param_bounds(
1462 bounds,
1463 &ImplTraitContext::Disallowed(ImplTraitPosition::Bound),
1464 ),
1465 in_where_clause: true,
1466 })
1467 }
1468 WherePredicate::EqPredicate(WhereEqPredicate { lhs_ty, rhs_ty, span }) => {
416331ca 1469 hir::WherePredicate::EqPredicate(hir::WhereEqPredicate {
5099ac24 1470 lhs_ty: self
f2b60f7d 1471 .lower_ty(lhs_ty, &ImplTraitContext::Disallowed(ImplTraitPosition::Type)),
5099ac24 1472 rhs_ty: self
f2b60f7d 1473 .lower_ty(rhs_ty, &ImplTraitContext::Disallowed(ImplTraitPosition::Type)),
487cf647 1474 span: self.lower_span(*span),
416331ca 1475 })
dfeec247
XL
1476 }
1477 }
1478 }
1479}