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