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