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